file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/4/0x0c6544Af9424C24549c57BD805C299635081eDE4/sources/contracts/QuoteStorage.sol
Store value in variable quoteToStore value to store/
function store(string memory quoteToStore) public { quote = quoteToStore; }
751,498
pragma solidity ^0.4.24; contract Coinevents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); event onBuy ( address playerAddress, uint256 begin, uint256 end, uint256 round, bytes32 playerName ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // settle the contract event onSettle( uint256 rid, uint256 ticketsout, address winner, uint256 luckynum, uint256 jackpot ); // settle the contract event onActivate( uint256 rid ); } contract LuckyCoin is Coinevents{ using SafeMath for *; using NameFilter for string; //**************** game settings **************** string constant public name = "LuckyCoin Super"; string constant public symbol = "LuckyCoin"; uint256 constant private rndGap_ = 2 hours; // round timer starts at this uint256 ticketstotal_ = 1500; // ticket total amonuts uint256 grouptotal_ = 250; // ticketstotal_ divend to six parts //uint ticketprice_ = 0.005 ether; // current ticket init price uint256 jackpot = 10 ether; uint256 public rID_= 0; // current round id number / total rounds that have happened uint256 _headtickets = 500; // head of 500, distributes valuet bool public activated_ = false; //address community_addr = 0x2b5006d3dce09dafec33bfd08ebec9327f1612d8; // community addr //address prize_addr = 0x2b5006d3dce09dafec33bfd08ebec9327f1612d8; // prize addr address community_addr = 0xfd76dB2AF819978d43e07737771c8D9E8bd8cbbF; // community addr address prize_addr = 0xfd76dB2AF819978d43e07737771c8D9E8bd8cbbF; // prize addr address activate_addr1 = 0xfd76dB2AF819978d43e07737771c8D9E8bd8cbbF; // activate addr1 address activate_addr2 = 0x6c7dfe3c255a098ea031f334436dd50345cfc737; // activate addr2 //address activate_addr2 = 0x2b5006d3dce09dafec33bfd08ebec9327f1612d8; // activate addr2 PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x748286a6a4cead7e8115ed0c503d77202eeeac6b); //**************** ROUND DATA **************** mapping (uint256 => Coindatasets.Round) public round_; // (rID => data) round data //**************** PLAYER DATA **************** event LogbuyNums(address addr, uint begin, uint end); mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Coindatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => Coindatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** ORDER DATA **************** mapping (uint256=>mapping(uint=> mapping(uint=>uint))) orders; // (rid=>pid=group=>ticketnum) constructor() public{ //round_[rID_].jackpot = 10 ether; } // callback function function () payable { // fllows addresses only can activate the game if (msg.sender == activate_addr1 || msg.sender == activate_addr2 ){ activate(); }else if(msg.value > 0){ //bet order // fetch player id address _addr = msg.sender; uint256 _codeLength; require(tx.origin == msg.sender, "sorry humans only origin"); assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only================="); determinePID(); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _ticketprice = getBuyPrice(); require(_ticketprice > 0); uint256 _tickets = msg.value / _ticketprice; require(_tickets > 0); // buy tickets require(activated_ == true, "its not ready yet. contact administrators"); require(_tickets <= ticketstotal_ - round_[rID_].tickets); buyTicket(_pID, plyr_[_pID].laff, _tickets); } } // purchase value limit modifier isWithinLimits(uint256 _eth, uint256 _tickets) { uint256 _ticketprice = getBuyPrice(); require(_eth >= _tickets * _ticketprice); require(_eth <= 100000000000000000000000); _; } modifier isTicketsLimits(uint256 _tickets){ require(_tickets <= ticketstotal_ - round_[rID_].tickets); _; } modifier isActivated(){ require(activated_, "not activate"); _; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; require(tx.origin == msg.sender, "sorry humans only origin"); assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only================="); _; } function buyXid(uint _tickets, uint256 _affCode) isHuman() isWithinLimits(msg.value, _tickets) isTicketsLimits(_tickets) isActivated public payable { // set up our tx event data and determine if player is new or not //Coindatasets.EventReturns memory _eventData_ = determinePID(_eventData_); determinePID(); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } buyTicket(_pID, _affCode, _tickets); } function buyXaddr(uint _tickets, address _affCode) isHuman() isWithinLimits(msg.value, _tickets) isTicketsLimits(_tickets) isActivated public payable { // set up our tx event data and determine if player is new or not //Coindatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // determine if player is new or not determinePID(); uint256 _affID; // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } buyTicket(_pID, _affID, _tickets); } function buyXname(uint _tickets, bytes32 _affCode) isHuman() isWithinLimits(msg.value, _tickets) isTicketsLimits(_tickets) isActivated public payable { // set up our tx event data and determine if player is new or not //Coindatasets.EventReturns memory _eventData_ = determinePID(_eventData_); determinePID(); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } buyTicket(_pID, _affID, _tickets); } function reLoadXaddr(uint256 _tickets, address _affCode) isHuman() isActivated isTicketsLimits(_tickets) public { // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == address(0) || _affCode == msg.sender){ _affID = plyr_[_pID].laff; } else{ // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } reloadTickets(_pID, _affID, _tickets); } function reLoadXname(uint256 _tickets, bytes32 _affCode) isHuman() isActivated isTicketsLimits(_tickets) public { // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name){ _affID = plyr_[_pID].laff; } else{ // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } reloadTickets(_pID, _affID, _tickets); } function reloadTickets(uint256 _pID, uint256 _affID, uint256 _tickets) isActivated private { //************** ****************** // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].start && _now < round_[_rID].end && round_[_rID].ended == false){ // call ticket uint256 _eth = getBuyPrice().mul(_tickets); //plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); reloadEarnings(_pID, _eth); ticket(_pID, _rID, _tickets, _affID, _eth); if (round_[_rID].tickets == ticketstotal_){ round_[_rID].ended = true; round_[_rID].end = now; endRound(); } }else if (_now > round_[_rID].end && round_[_rID].ended == false){ // end the round (distributes pot) & start new round round_[_rID].ended = true; endRound(); } } function withdraw() isHuman() public { // setup local rID //uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet _eth = withdrawEarnings(_pID); if (_eth > 0){ plyr_[_pID].addr.transfer(_eth); emit Coinevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } function reloadEarnings(uint256 _pID, uint256 _eth) private returns(uint256) { // update gen vault updateTicketVault(_pID, plyr_[_pID].lrnd); uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); require(_earnings >= _eth, "earnings too lower"); if (plyr_[_pID].gen >= _eth) { plyr_[_pID].gen = plyr_[_pID].gen.sub(_eth); return; }else{ _eth = _eth.sub(plyr_[_pID].gen); plyr_[_pID].gen = 0; } if (plyr_[_pID].aff >= _eth){ plyr_[_pID].aff = plyr_[_pID].aff.sub(_eth); return; }else{ _eth = _eth.sub(plyr_[_pID].aff); plyr_[_pID].aff = 0; } plyr_[_pID].win = plyr_[_pID].win.sub(_eth); } function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateTicketVault(_pID, plyr_[_pID].lrnd); uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; // winner plyr_[_pID].gen = 0; //ticket valuet plyr_[_pID].aff = 0; // aff player } return(_earnings); } // aquire buy ticket price function getBuyPrice() public view returns(uint256) { return round_[rID_].jackpot.mul(150) / 100 / 1500; } /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyTicket( uint256 _pID, uint256 _affID, uint256 _tickets) private { //************** ****************** // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].start && _now < round_[_rID].end){ // call ticket ticket(_pID, _rID, _tickets, _affID, msg.value); if (round_[_rID].tickets == ticketstotal_){ round_[_rID].ended = true; round_[_rID].end = now; endRound(); } }else if (_now > round_[_rID].end && round_[_rID].ended == false){ // end the round (distributes pot) & start new round round_[_rID].ended = true; //_eventData_ = endRound(_eventData_); endRound(); // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } //ticket(_pID, _rID, _tickets, _affID, msg.value); } function ticket(uint256 _pID, uint256 _rID, uint256 _tickets, uint256 _affID, uint256 _eth) private { // if player is new to round if (plyrRnds_[_pID][_rID].tickets == 0){ managePlayer(_pID); round_[rID_].playernums += 1; plyrRnds_[_affID][_rID].affnums += 1; } // ********** buy ticket ************* uint tickets = round_[rID_].tickets; uint groups = (tickets + _tickets - 1) / grouptotal_ - tickets / grouptotal_; uint offset = tickets / grouptotal_; if (groups == 0){ if (((tickets + _tickets) % grouptotal_) == 0){ orders[rID_][_pID][offset] = calulateXticket(orders[rID_][_pID][offset], grouptotal_, tickets % grouptotal_); }else{ orders[rID_][_pID][offset] = calulateXticket(orders[rID_][_pID][offset], (tickets + _tickets) % grouptotal_, tickets % grouptotal_); } }else{ for(uint256 i = 0; i < groups + 1; i++){ if (i == 0){ orders[rID_][_pID][offset+i] = calulateXticket(orders[rID_][_pID][offset + i], grouptotal_, tickets % grouptotal_); } if (i > 0 && i < groups){ orders[rID_][_pID][offset + i] = calulateXticket(orders[rID_][_pID][offset + i], grouptotal_, 0); } if (i == groups){ if (((tickets + _tickets) % grouptotal_) == 0){ orders[rID_][_pID][offset + i] = calulateXticket(orders[rID_][_pID][offset + i], grouptotal_, 0); }else{ orders[rID_][_pID][offset + i] = calulateXticket(orders[rID_][_pID][offset + i], (tickets + _tickets) % grouptotal_, 0); } } } } if (round_[rID_].tickets < _headtickets){ if (_tickets.add(round_[rID_].tickets) <= _headtickets){ plyrRnds_[_pID][_rID].luckytickets = _tickets.add(plyrRnds_[_pID][_rID].luckytickets); } else{ plyrRnds_[_pID][_rID].luckytickets = (_headtickets - round_[rID_].tickets).add(plyrRnds_[_pID][_rID].luckytickets); } } // set up purchase tickets round_[rID_].tickets = _tickets.add(round_[rID_].tickets); plyrRnds_[_pID][_rID].tickets = _tickets.add(plyrRnds_[_pID][_rID].tickets); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); round_[rID_].blocknum = block.number; // distributes valuet distributeVault(_pID, rID_, _affID, _eth, _tickets); // order event log //emit onBuy(msg.sender, tickets+1, tickets +_tickets,_rID, _eth, plyr_[_pID].name); emit Coinevents.onBuy(msg.sender, tickets+1, tickets +_tickets,_rID, plyr_[_pID].name); } function distributeVault(uint256 _pID, uint256 _rID, uint256 _affID, uint256 _eth, uint256 _tickets) private { // distributes gen uint256 _gen = 0; uint256 _genvault = 0; uint256 ticketprice_ = getBuyPrice(); if (round_[_rID].tickets > _headtickets){ if (round_[_rID].tickets.sub(_tickets) > _headtickets){ _gen = _tickets; //plyrRnds_[_pID][_rID].luckytickets = }else{ _gen = round_[_rID].tickets.sub(_headtickets); } } if (_gen > 0){ //_genvault = (((_gen / _tickets).mul(_eth)).mul(20)) / 100; // 20 % to gen tickets _genvault = ((ticketprice_ * _gen).mul(20)) / 100; round_[_rID].mask = _genvault.add(round_[_rID].mask); // update mask } uint256 _aff = _eth / 10; //to================10%(aff) uint256 _com = _eth / 20; //to================5%(community) uint256 _found = _eth.mul(32) / 100; round_[_rID].found = _found.add(round_[_rID].found); //to============prize found if (_affID != 0){ plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); community_addr.transfer(_com); }else{ _com = _com.add(_aff); community_addr.transfer(_com); } // ============to perhaps next round pool uint256 _nextpot = _eth.sub(_genvault); if (_affID != 0){ _nextpot = _nextpot.sub(_aff); } _nextpot = _nextpot.sub(_com); _nextpot = _nextpot.sub(_found); round_[_rID].nextpot = _nextpot.add(round_[_rID].nextpot); // next round pool } function calulateXticket(uint256 _target, uint256 _start, uint256 _end) pure private returns(uint256){ return _target ^ (2 ** _start - 2 ** _end); } function endRound() private { // setup local rID uint256 _rID = rID_; uint256 prize_callback = 0; round_[_rID].lucknum = randNums(); // 1. if win if (round_[_rID].tickets >= round_[_rID].lucknum){ // community_addr.transfer(round_[_rID].income.sub(_com).sub(_gen)); // need administrators take in 10 ETH activate next round prize_callback = round_[_rID].found.add(round_[_rID].nextpot); if (prize_callback > 0) { prize_addr.transfer(prize_callback); activated_ = false; // need administrators to activate emit onSettle(_rID, round_[_rID].tickets, address(0), round_[_rID].lucknum, round_[_rID].jackpot); } }else{ // 2. if nobody win // directly start next round prize_callback = round_[_rID].found; if (prize_callback > 0) { prize_addr.transfer(prize_callback); } rID_ ++; _rID ++; round_[_rID].start = now; round_[_rID].end = now.add(rndGap_); round_[_rID].jackpot = round_[_rID-1].jackpot.add(round_[_rID-1].nextpot); emit onSettle(_rID-1, round_[_rID-1].tickets, address(0), round_[_rID-1].lucknum, round_[_rID-1].jackpot); } } /** * @dev moves any unmasked earnings to ticket vault. updates earnings */ // _pID: player pid _rIDlast: last roundid function updateTicketVault(uint256 _pID, uint256 _rIDlast) private{ uint256 _gen = (plyrRnds_[_pID][_rIDlast].luckytickets.mul(round_[_rIDlast].mask / _headtickets)).sub(plyrRnds_[_pID][_rIDlast].mask); uint256 _jackpot = 0; if (judgeWin(_rIDlast, _pID) && address(round_[_rIDlast].winner) == 0) { _jackpot = round_[_rIDlast].jackpot; round_[_rIDlast].winner = msg.sender; } plyr_[_pID].gen = _gen.add(plyr_[_pID].gen); // ticket valuet plyr_[_pID].win = _jackpot.add(plyr_[_pID].win); // player win plyrRnds_[_pID][_rIDlast].mask = plyrRnds_[_pID][_rIDlast].mask.add(_gen); } function managePlayer(uint256 _pID) private { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateTicketVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update ticket) * @return earnings in wei format */ //计算每轮中pid前500ticket的分红 function calcTicketEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { // per round ticket valuet return (plyrRnds_[_pID][_rIDlast].luckytickets.mul(round_[_rIDlast].mask / _headtickets)).sub(plyrRnds_[_pID][_rIDlast].mask); } //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ function activate() isHuman() public payable { // can only be ran once require(msg.sender == activate_addr1 || msg.sender == activate_addr2); require(activated_ == false, "LuckyCoin already activated"); //uint256 _jackpot = 10 ether; require(msg.value == jackpot, "activate game need 10 ether"); if (rID_ != 0) { require(round_[rID_].tickets >= round_[rID_].lucknum, "nobody win"); } //activate the contract activated_ = true; //lets start first round rID_ ++; round_[rID_].start = now; round_[rID_].end = now + rndGap_; round_[rID_].jackpot = msg.value; emit onActivate(rID_); } /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } //==============================PLAYER========================================== /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID() private //returns (Coindatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of luckycoin if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true //_eventData_.compressedData = _eventData_.compressedData + 1; } //return (_eventData_); } // only support Name by name function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit Coinevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit Coinevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end){ return( (round_[_rID].end).sub(_now) ); } else return(0); } function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bool) { // setup local rID uint256 _rID = rID_; return ( rID_, round_[_rID].tickets, round_[_rID].start, round_[_rID].end, round_[_rID].jackpot, round_[_rID].nextpot, round_[_rID].lucknum, round_[_rID].mask, round_[_rID].playernums, round_[_rID].winner, round_[_rID].ended ); } function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; uint256 _lrnd = plyr_[_pID].lrnd; uint256 _jackpot = 0; if (judgeWin(_lrnd, _pID) && address(round_[_lrnd].winner) == 0){ _jackpot = round_[_lrnd].jackpot; } return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].tickets, //2 plyr_[_pID].win.add(_jackpot), //3 plyr_[_pID].gen.add(calcTicketEarnings(_pID, _lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth, //6 plyrRnds_[_pID][_rID].affnums // 7 ); } // generate a number between 1-1500 function randNums() public view returns(uint256) { return uint256(keccak256(block.difficulty, now, block.coinbase)) % ticketstotal_ + 1; } // search user if win function judgeWin(uint256 _rid, uint256 _pID)private view returns(bool){ uint256 _group = (round_[_rid].lucknum -1) / grouptotal_; uint256 _temp = round_[_rid].lucknum % grouptotal_; if (_temp == 0){ _temp = grouptotal_; } if (orders[_rid][_pID][_group] & (2 **(_temp-1)) == 2 **(_temp-1)){ return true; }else{ return false; } } // search the tickets owns function searchtickets()public view returns(uint256, uint256, uint256, uint256,uint256, uint256){ uint256 _pID = pIDxAddr_[msg.sender]; return ( orders[rID_][_pID][0], orders[rID_][_pID][1], orders[rID_][_pID][2], orders[rID_][_pID][3], orders[rID_][_pID][4], orders[rID_][_pID][5] ); } // search the tickets by address function searchTicketsXaddr(address addr) public view returns(uint256, uint256, uint256, uint256,uint256, uint256){ uint256 _pID = pIDxAddr_[addr]; return ( orders[rID_][_pID][0], orders[rID_][_pID][1], orders[rID_][_pID][2], orders[rID_][_pID][3], orders[rID_][_pID][4], orders[rID_][_pID][5] ); } } library Coindatasets { struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Round { uint256 tickets; // already purchase ticket bool ended; // has round end function been ran uint256 jackpot; // eth to pot, perhaps next round pot uint256 start; // time round started uint256 end; // time ends/ended address winner; //win address uint256 mask; // global mask uint256 found; // jackpot found uint256 lucknum; // win num uint256 nextpot; // next pot uint256 blocknum; // current blocknum uint256 playernums; // playernums } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used uint256 luckytickets; // head 500 will acquire distributes vault } struct PotSplit { uint256 community; // % of pot thats paid to key holders of current round uint256 gen; // % of pot thats paid to tickets holders uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round uint256 tickets; // tickets uint256 mask; // player mask, uint256 affnums; uint256 luckytickets; // player luckytickets } } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
returns time left. dont spam this, you'll ddos yourself from your node provider -functionhash- 0xc7e284b8 return time left in seconds/ setup local rID grab time
{ uint256 _rID = rID_; uint256 _now = now; function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable } function getTimeLeft() public view returns(uint256) if (_now < round_[_rID].end){ return( (round_[_rID].end).sub(_now) ); } else return(0); }
13,020,767
./partial_match/1/0x1D72D4746647B7Fe84e2bCDEfD96C119FB9CB0f0/sources/DeltaTimeInventory.sol
Public function to mint one non fungible token id Reverts if the given token ID is not non fungible token id to address recipient that will own the minted tokens tokenId uint256 ID of the token to be minted byteUri bytes32 Concatenated metadata URI of nft to be minted/
function mintNonFungible(address to, uint256 tokenId, bytes32 byteUri) external onlyMinter { _mintNonFungible(to, tokenId, byteUri); }
4,462,475
./partial_match/42220/0xCdE5039e3AcB3483aEebEBd59Cf6936056c455D4/sources/Users/pahor/repo/4/celo-monorepo/packages/protocol/contracts/governance/Election.sol
Marks a group eligible for electing validators. group The address of the validator group. lesser The address of the group that has received fewer votes than this group. greater The address of the group that has received more votes than this group./
function markGroupEligible(address group, address lesser, address greater) external onlyRegisteredContract(VALIDATORS_REGISTRY_ID) { uint256 value = getTotalVotesForGroup(group); votes.total.eligible.insert(group, value, lesser, greater); emit ValidatorGroupMarkedEligible(group); }
3,496,815
./full_match/42/0x6a3E62035aFD98f6eDbb9d9102B576D90178ee44/sources/Documents/DEV/PRUF/PRUF_TRUFFLE/contracts/PRUF_SPLITTER.sol
doubles pruf balance at snapshot snapshotID/^^^^^^^checks^^^^^^^^^^^^^^^^effects^^^^^^^^^^^^^^^^Interactions^^^^^^^^^
function splitMyPruf() external whenNotPaused { require( hasSplit[msg.sender] == 0, "SPLIT:SMP: Caller address has already been split" ); uint256 balanceAtSnapshot = UTIL_TKN.balanceOfAt(msg.sender, 1); }
9,592,748
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "./UniverseERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract UniverseERC721Core is UniverseERC721 { using Counters for Counters.Counter; Counters.Counter private _tokenIds; constructor(string memory _tokenName, string memory _tokenSymbol) UniverseERC721(_tokenName, _tokenSymbol) {} function batchMint( address receiver, string[] calldata tokenURIs, Fee[] memory fees ) external override returns (uint256[] memory) { require(tokenURIs.length <= 40, "Cannot mint more than 40"); uint256[] memory mintedTokenIds = new uint256[](tokenURIs.length); for (uint256 i = 0; i < tokenURIs.length; i++) { uint256 tokenId = mint(receiver, tokenURIs[i], fees); mintedTokenIds[i] = tokenId; } return mintedTokenIds; } function batchMintMultipleReceivers( address[] calldata receivers, string[] calldata tokenURIs, Fee[] memory fees ) external override returns (uint256[] memory) { require(tokenURIs.length <= 40, "Cannot mint more than 40"); require(receivers.length == tokenURIs.length, "Wrong config"); uint256[] memory mintedTokenIds = new uint256[](tokenURIs.length); for (uint256 i = 0; i < tokenURIs.length; i++) { uint256 tokenId = mint(receivers[i], tokenURIs[i], fees); mintedTokenIds[i] = tokenId; } return mintedTokenIds; } function batchMintWithDifferentFees( address receiver, string[] calldata tokenURIs, Fee[][] memory fees ) external override returns (uint256[] memory) { require(tokenURIs.length <= 40, "Cannot mint more than 40"); require(tokenURIs.length == fees.length, "Wrong fee config"); uint256[] memory mintedTokenIds = new uint256[](tokenURIs.length); for (uint256 i = 0; i < tokenURIs.length; i++) { uint256 tokenId = mint(receiver, tokenURIs[i], fees[i]); mintedTokenIds[i] = tokenId; } return mintedTokenIds; } function mint( address receiver, string memory tokenURI, Fee[] memory fees ) public override returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(receiver, newItemId); _setTokenURI(newItemId, tokenURI); if (fees.length > 0) { _registerFees(newItemId, fees); // The ERC2981 standard supports only one split, so we set the first value _setTokenRoyalty(newItemId, fees[0].recipient, fees[0].value); } // We use tx.origin to set the creator, as there are cases when a contract can call this funciton creatorOf[newItemId] = tx.origin; emit UniverseERC721TokenMinted(newItemId, tokenURI, receiver, block.timestamp); return newItemId; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ERC721Consumable.sol"; import "./HasSecondarySaleFees.sol"; import "./ERC2981Royalties.sol"; contract UniverseERC721 is ERC721Enumerable, ERC721URIStorage, ERC721Consumable, Ownable, HasSecondarySaleFees, ERC2981Royalties { using Counters for Counters.Counter; Counters.Counter private _tokenIds; // Mapping from token ID to creator address; mapping(uint256 => address) public creatorOf; // Mapping from token ID to torrent magnet links mapping (uint256 => string) public torrentMagnetLinkOf; event UniverseERC721TokenMinted( uint256 tokenId, string tokenURI, address receiver, uint256 time ); modifier onlyCreator(uint256 tokenId) { require(msg.sender == creatorOf[tokenId], "Not called from the creator"); _; } constructor(string memory _tokenName, string memory _tokenSymbol) ERC721(_tokenName, _tokenSymbol) {} function batchMint( address receiver, string[] calldata tokenURIs, Fee[] memory fees ) external virtual onlyOwner returns (uint256[] memory) { require(tokenURIs.length <= 40, "Cannot mint more than 40"); uint256[] memory mintedTokenIds = new uint256[](tokenURIs.length); for (uint256 i = 0; i < tokenURIs.length; i++) { uint256 tokenId = mint(receiver, tokenURIs[i], fees); mintedTokenIds[i] = tokenId; } return mintedTokenIds; } function batchMintMultipleReceivers( address[] calldata receivers, string[] calldata tokenURIs, Fee[] memory fees ) external virtual onlyOwner returns (uint256[] memory) { require(tokenURIs.length <= 40, "Cannot mint more than 40"); require(receivers.length == tokenURIs.length, "Wrong config"); uint256[] memory mintedTokenIds = new uint256[](tokenURIs.length); for (uint256 i = 0; i < tokenURIs.length; i++) { uint256 tokenId = mint(receivers[i], tokenURIs[i], fees); mintedTokenIds[i] = tokenId; } return mintedTokenIds; } function batchMintWithDifferentFees( address receiver, string[] calldata tokenURIs, Fee[][] memory fees ) external virtual onlyOwner returns (uint256[] memory) { require(tokenURIs.length <= 40, "Cannot mint more than 40"); require(tokenURIs.length == fees.length, "Wrong fee config"); uint256[] memory mintedTokenIds = new uint256[](tokenURIs.length); for (uint256 i = 0; i < tokenURIs.length; i++) { uint256 tokenId = mint(receiver, tokenURIs[i], fees[i]); mintedTokenIds[i] = tokenId; } return mintedTokenIds; } function updateTorrentMagnetLink(uint256 _tokenId, string memory _torrentMagnetLink) external virtual onlyCreator(_tokenId) returns (string memory) { torrentMagnetLinkOf[_tokenId] = _torrentMagnetLink; return _torrentMagnetLink; } function ownedTokens(address ownerAddress) external view returns (uint256[] memory) { uint256 tokenBalance = balanceOf(ownerAddress); uint256[] memory tokens = new uint256[](tokenBalance); for (uint256 i = 0; i < tokenBalance; i++) { uint256 tokenId = tokenOfOwnerByIndex(ownerAddress, i); tokens[i] = tokenId; } return tokens; } function mint( address receiver, string memory newTokenURI, Fee[] memory fees ) public virtual onlyOwner returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(receiver, newItemId); _setTokenURI(newItemId, newTokenURI); if (fees.length > 0) { _registerFees(newItemId, fees); // The ERC2981 standard supports only one split, so we set the first value _setTokenRoyalty(newItemId, fees[0].recipient, fees[0].value); } // We use tx.origin to set the creator, as there are cases when a contract can call this funciton creatorOf[newItemId] = tx.origin; emit UniverseERC721TokenMinted(newItemId, newTokenURI, receiver, block.timestamp); return newItemId; } function _registerFees(uint256 _tokenId, Fee[] memory _fees) internal { require(_fees.length <= 5, "No more than 5 recipients"); address[] memory recipients = new address[](_fees.length); uint256[] memory bps = new uint256[](_fees.length); uint256 sum = 0; for (uint256 i = 0; i < _fees.length; i++) { require(_fees[i].recipient != address(0x0), "Recipient should be present"); require(_fees[i].value != 0, "Fee value should be positive"); sum = sum + _fees[i].value; fees[_tokenId].push(_fees[i]); recipients[i] = _fees[i].recipient; bps[i] = _fees[i].value; } require(sum <= 3000, "Fee should be less than 30%"); if (_fees.length > 0) { emit SecondarySaleFees(_tokenId, recipients, bps); } } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Storage, ERC721, ERC721Enumerable, ERC721Consumable) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view virtual override(ERC721URIStorage, ERC721) returns (string memory) { return super.tokenURI(tokenId); } function _burn(uint256 tokenId) internal virtual override(ERC721URIStorage, ERC721) { return super._burn(tokenId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721, ERC721Consumable) { return super._beforeTokenTransfer(from, to, tokenId); } } // 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 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: 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)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } //SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./interfaces/IERC721Consumable.sol"; abstract contract ERC721Consumable is IERC721Consumable, ERC721 { // Mapping from token ID to consumer address mapping (uint256 => address) _tokenConsumers; /** * @dev See {IERC721Consumable-consumerOf} */ function consumerOf(uint256 _tokenId) view external returns (address) { require(_exists(_tokenId), "ERC721Consumable: consumer query for nonexistent token"); return _tokenConsumers[_tokenId]; } /** * @dev See {IERC721Consumable-changeConsumer} */ function changeConsumer(address _consumer, uint256 _tokenId) external { address owner = this.ownerOf(_tokenId); require(msg.sender == owner || msg.sender == getApproved(_tokenId) || isApprovedForAll(owner, msg.sender), "ERC721Consumable: changeConsumer caller is not owner nor approved"); _changeConsumer(owner, _consumer, _tokenId); } /** * @dev Changes the consumer * Requirement: `tokenId` must exist */ function _changeConsumer(address _owner, address _consumer, uint256 _tokenId) internal { _tokenConsumers[_tokenId] = _consumer; emit ConsumerChanged(_owner, _consumer, _tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { return interfaceId == type(IERC721Consumable).interfaceId || super.supportsInterface(interfaceId); } function _beforeTokenTransfer(address _from, address _to, uint256 _tokenId) internal virtual override (ERC721) { super._beforeTokenTransfer(_from, _to, _tokenId); _changeConsumer(_from, address(0), _tokenId); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol"; contract HasSecondarySaleFees is ERC165Storage { struct Fee { address payable recipient; uint96 value; } // id => fees mapping (uint256 => Fee[]) public fees; event SecondarySaleFees(uint256 tokenId, address[] recipients, uint[] bps); /* * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * * => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584 */ bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584; constructor() { _registerInterface(_INTERFACE_ID_FEES); } function getFeeRecipients(uint256 id) external view returns (address payable[] memory) { Fee[] memory _fees = fees[id]; address payable[] memory result = new address payable[](_fees.length); for (uint i = 0; i < _fees.length; i++) { result[i] = _fees[i].recipient; } return result; } function getFeeBps(uint256 id) external view returns (uint[] memory) { Fee[] memory _fees = fees[id]; uint[] memory result = new uint[](_fees.length); for (uint i = 0; i < _fees.length; i++) { result[i] = _fees[i].value; } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol"; import "./interfaces/IERC2981Royalties.sol"; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 abstract contract ERC2981Royalties is ERC165Storage, IERC2981Royalties { struct RoyaltyInfo { address recipient; uint24 amount; } mapping(uint256 => RoyaltyInfo) internal _royalties; bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; constructor() { _registerInterface(_INTERFACE_ID_ERC2981); } /// @dev Sets token royalties /// @param tokenId the token id fir which we register the royalties /// @param recipient recipient of the royalties /// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0) function _setTokenRoyalty( uint256 tokenId, address recipient, uint256 value ) internal { require(value <= 10000, "ERC2981Royalties: Too high"); _royalties[tokenId] = RoyaltyInfo(recipient, uint24(value)); } function royaltyInfo(uint256 tokenId, uint256 value) external view override returns (address receiver, uint256 royaltyAmount) { RoyaltyInfo memory royalties = _royalties[tokenId]; receiver = royalties.recipient; royaltyAmount = (value * royalties.amount) / 10000; } } // 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 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // 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 pragma solidity 0.8.11; /// @title ERC-721 Consumer Role extension /// Note: the ERC-165 identifier for this interface is 0x953c8dfa interface IERC721Consumable { /* is ERC721 */ /// @notice Emitted when `owner` changes the `consumer` of an NFT /// The zero address for consumer indicates that there is no consumer address /// When a Transfer event emits, this also indicates that the consumer address /// for that NFT (if any) is set to none event ConsumerChanged(address indexed owner, address indexed consumer, uint256 indexed tokenId); /// @notice Get the consumer address of an NFT /// @dev The zero address indicates that there is no consumer /// Throws if `_tokenId` is not a valid NFT /// @param _tokenId The NFT to get the consumer address for /// @return The consumer address for this NFT, or the zero address if there is none function consumerOf(uint256 _tokenId) external view returns (address); /// @notice Change or reaffirm the consumer address for an NFT /// @dev The zero address indicates there is no consumer address /// Throws unless `msg.sender` is the current NFT owner, an authorised /// operator of the current owner or approved address /// Throws if `_tokenId` is not valid NFT /// @param _consumer The new consumer of the NFT function changeConsumer(address _consumer, uint256 _tokenId) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Storage.sol) pragma solidity ^0.8.0; import "./ERC165.sol"; /** * @dev Storage based implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Storage is ERC165 { /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return super.supportsInterface(interfaceId) || _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /// @title IERC2981Royalties /// @dev Interface for the ERC2981 - Token Royalty standard interface IERC2981Royalties { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _value - the sale price of the NFT asset specified by _tokenId /// @return _receiver - address of who should be sent the royalty payment /// @return _royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 _tokenId, uint256 _value) external view returns (address _receiver, uint256 _royaltyAmount); }
Changes the consumer Requirement: `tokenId` must exist/
function _changeConsumer(address _owner, address _consumer, uint256 _tokenId) internal { _tokenConsumers[_tokenId] = _consumer; emit ConsumerChanged(_owner, _consumer, _tokenId); }
505,599
pragma solidity ^0.4.18; library SafeMath { //SafeMath library for preventing overflow when dealing with uint256 in solidity /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { //ERC20 contract used as an interface. Implementation of functions provided in the derived contract. string public NAME; string public SYMBOL; uint8 public DECIMALS = 18; // 18 DECIMALS is the strongly suggested default, avoid changing it //total supply (TOTALSUPPLY) is declared private and can be accessed via totalSupply() uint private TOTALSUPPLY; // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account //This is a mapping of a mapping // This mapping keeps track of the allowances given mapping(address => mapping (address => uint256)) allowed; //*** ERC20 FUNCTIONS ***// //1 //Allows an instance of a contract to calculate and return the total amount //of the token that exists. function totalSupply() public constant returns (uint256 _totalSupply); //2 //Allows a contract to store and return the balance of the provided address (parameter) function balanceOf(address _owner) public constant returns (uint256 balance); //3 //Lets the caller send a given amount(_amount) of the token to another address(_to). //Note: returns a boolean indicating whether transfer was successful function transfer(address _to, uint256 _value) public returns (bool success); //4 //Owner "approves" the given address to withdraw instances of the tokens from the owners address function approve(address _spender, uint256 _value) public returns (bool success); //5 //Lets an "approved" address transfer the approved amount from the address that called approve() function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); //6 //returns the amount of tokens approved by the owner that can *Still* be transferred //to the spender's account using the transferFrom method. function allowance(address _owner, address _spender) public constant returns (uint256 remaining); //***ERC20 Events***// //Event 1 // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); //Event 2 // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; //Event triggered when owner address is changed. 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 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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Bitcub is Ownable, ERC20 { using SafeMath for uint256; string public constant NAME = "Bitcub"; string public constant SYMBOL = "BCU"; uint8 public constant DECIMALS = 18; // 18 DECIMALS is the strongly suggested default, avoid changing it //total supply (TOTALSUPPLY) is declared private and constant and can be accessed via totalSupply() uint private constant TOTALSUPPLY = 500000000*(10**18); // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account //This is a mapping of a mapping // This mapping keeps track of the allowances given mapping(address => mapping (address => uint256)) allowed; //Constructor FOR BITCUB TOKEN constructor() public { //establishes ownership of the contract upon creation Ownable(msg.sender); /* IMPLEMENTING ALLOCATION OF TOKENS */ balances[0xaf0A558783E92a1aEC9dd2D10f2Dc9b9AF371212] = 150000000*(10**18); /* Transfer Events for the allocations */ emit Transfer(address(0), 0xaf0A558783E92a1aEC9dd2D10f2Dc9b9AF371212, 150000000*(10**18)); //sends all the unallocated tokens (350,000,000 tokens) to the address of the contract creator (The Crowdsale Contract) balances[msg.sender] = TOTALSUPPLY.sub(150000000*(10**18)); //Transfer event for sending tokens to Crowdsale Contract emit Transfer(address(0), msg.sender, TOTALSUPPLY.sub(150000000*(10**18))); } //*** ERC20 FUNCTIONS ***// //1 /** * @dev total number of tokens in existence */ function totalSupply() public constant returns (uint256 _totalSupply) { //set the named return variable as the global variable totalSupply _totalSupply = TOTALSUPPLY; } //2 /** * @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]; } //3 /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ //Note: returns a boolean indicating whether transfer was successful function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); //not sending to burn address require(_value <= balances[msg.sender]); // If the sender has sufficient funds to send require(_value>0);// and the amount is not zero or negative // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } //4 //Owner "approves" the given address to withdraw instances of the tokens from the owners address /** * @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; } //5 //Lets an "approved" address transfer the approved amount from the address that called approve() /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } //6 /** * @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]; } //additional functions for altering allowances /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } //***ERC20 Events***// //Event 1 // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); //Event 2 // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); } //Using OpenZeppelin Crowdsale contract as a reference and altered, also using ethereum.org/Crowdsale as a reference. /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. //The original OpenZeppelin contract requires a MintableToken that will be * minted as contributions arrive, note that the crowdsale contract * must be owner of the token in order to be able to mint it. //This version does not use a MintableToken. */ contract BitcubCrowdsale is Ownable { using SafeMath for uint256; // The token being sold Bitcub public token; //The amount of the tokens remaining that are unsold. uint256 remainingTokens = 350000000 *(10**18); // start and end timestamps where investments are allowed (inclusive), as well as timestamps for beginning and end of presale tiers uint256 public startTime; uint256 public endTime; uint256 public tier1Start; uint256 public tier1End; uint256 public tier2Start; uint256 public tier2End; // address where funds are collected address public etherWallet; // address where unsold tokens are sent address public tokenWallet; // how many token units a buyer gets per wei uint256 public rate = 100; // amount of raised money in wei uint256 public weiRaised; //minimum purchase for an buyer in amount of ether (1 token) uint256 public minPurchaseInEth = 0.01 ether; //maximum investment for an investor in amount of tokens //To set max investment to 5% of total, it is 25,000,000 tokens, which is 250000 ETH uint256 public maxInvestment = 250000 ether; //mapping to keep track of the amount invested by each address. mapping (address => uint256) internal invested; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //Constructor for crowdsale. constructor() public { //hard coded times and wallets startTime = now ; tier1Start = startTime ; tier1End = 1528416000 ; //midnight on 2018-06-08 GMT tier2Start = tier1End; tier2End = 1532131200 ; //midnight on 2018-07-21 GMT endTime = 1538265600 ; //midnight on 2018-09-30 GMT etherWallet = 0xaf0A558783E92a1aEC9dd2D10f2Dc9b9AF371212; //Bitcub Reserve Wallet tokenWallet = 0xaf0A558783E92a1aEC9dd2D10f2Dc9b9AF371212; //Bitcub Reserve Wallet require(startTime >= now); require(endTime >= startTime); require(etherWallet != address(0)); //establishes ownership of the contract upon creation Ownable(msg.sender); //calls the function to create the token contract itself. token = createTokenContract(); } function createTokenContract() internal returns (Bitcub) { // Create Token contract // The amount for sale will be assigned to the crowdsale contract, the reserves will be sent to the Bitcub Wallet return new Bitcub(); } // fallback function can be used to buy tokens //This function is called whenever ether is sent to this contract address. function () external payable { //calls the buyTokens function with the address of the sender as the beneficiary address buyTokens(msg.sender); } //This function is called after the ICO has ended to send the unsold Tokens to the specified address function finalizeCrowdsale() public onlyOwner returns (bool) { require(hasEnded()); require(token.transfer(tokenWallet, remainingTokens)); return true; } // low level token purchase function //implements the logic for the token buying function buyTokens(address beneficiary) public payable { //tokens cannot be burned by sending to 0x0 address require(beneficiary != address(0)); //token must adhere to the valid restrictions of the validPurchase() function, ie within time period and buying tokens within max/min limits require(validPurchase(beneficiary)); uint256 weiAmount = msg.value; // calculate token amount to be bought uint256 tokens = getTokenAmount(weiAmount); //Logic so that investors must purchase at least 1 token. require(weiAmount >= minPurchaseInEth); //Token transfer require(token.transfer(beneficiary, tokens)); // update state //increment the total ammount raised by the amount of this transaction weiRaised = weiRaised.add(weiAmount); //decrease the amount of remainingTokens by the amount of tokens sold remainingTokens = remainingTokens.sub(tokens); //increase the investment total of the buyer invested[beneficiary] = invested[beneficiary].add(msg.value); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); //transfer the ether received to the specified recipient address forwardFunds(); } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } // Function to have a way to add business logic to your crowdsale when buying function getTokenAmount(uint256 weiAmount) internal returns(uint256) { //Logic for pricing based on the Tiers of the crowdsale // These bonus amounts and the number of tiers itself can be changed /*This means that: - If you purchase within the tier 1 ICO (earliest tier) you receive a 20% bonus in your token purchase. - If you purchase within the tier 2 ICO (later tier) you receive a 10% bonus in your token purchase. - If you purchase outside of any of the defined bonus tiers then you receive the original rate of tokens (1 token per 0.01 ether) */ if (now>=tier1Start && now < tier1End) { rate = 120; }else if (now>=tier2Start && now < tier2End) { rate = 110; }else { rate = 100; } return weiAmount.mul(rate); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { etherWallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase(address beneficiary) internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinMaxInvestment = ( invested[beneficiary].add(msg.value) <= maxInvestment ); return withinPeriod && nonZeroPurchase && withinMaxInvestment; } }
send ether to the fund collection wallet override to create custom fund forwarding mechanisms
function forwardFunds() internal { etherWallet.transfer(msg.value); }
1,694,746
/* * /$$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ * | $$__ $$ /$$__ $$| $$__ $$| $$__ $$ /$$__ $$| $$ /$$/ /$$__ $$ * | $$ \ $$| $$ \ $$| $$ \ $$| $$ \ $$|__/ \ $$| $$ /$$/ | $$ \ $$ * | $$$$$$$/| $$$$$$$$| $$$$$$$/| $$$$$$$/ /$$$$$/| $$$$$/ | $$$$$$$$ * | $$____/ | $$__ $$| $$____/ | $$__ $$ |___ $$| $$ $$ | $$__ $$ * | $$ | $$ | $$| $$ | $$ \ $$ /$$ \ $$| $$\ $$ | $$ | $$ * | $$ | $$ | $$| $$ | $$ | $$| $$$$$$/| $$ \ $$| $$ | $$ * |__/ |__/ |__/|__/ |__/ |__/ \______/ |__/ \__/|__/ |__/ * * * * /$$$$$$$$ /$$ * | $$_____/|__/ * | $$ /$$ /$$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$$ /$$$$$$ * | $$$$$ | $$| $$__ $$ |____ $$| $$__ $$ /$$_____/ /$$__ $$ * | $$__/ | $$| $$ \ $$ /$$$$$$$| $$ \ $$| $$ | $$$$$$$$ * | $$ | $$| $$ | $$ /$$__ $$| $$ | $$| $$ | $$_____/ * | $$ | $$| $$ | $$| $$$$$$$| $$ | $$| $$$$$$$| $$$$$$$ * |__/ |__/|__/ |__/ \_______/|__/ |__/ \_______/ \_______/ * * Paprica Finance - created by Sushi ecosystem. * */ pragma solidity ^0.6.12; /* * @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; } } /** * @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 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; } } /** * @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); } } } } /** * @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"); } } } /** * @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; } } /** * @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; uint public startDate; uint public bonusEnds; uint public endDate; uint public hardcap; uint public forPAPR3KAholders; address private _dewpresale; address public newun; uint public reva; /** * @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; //for presale endDate = now + 2 weeks; // presale days bonusEnds = now + 5 days; // presale bonus days hardcap = 12000 ether; // 470 PAPR3KA2 - max. pre-sale supply! forPAPR3KAholders = 12000 ether; // 470 PAPR3KA2 - for PAPR3KA holders! _dewpresale = 0x23a1287864027027A35b18C1fb65D482e71f2740; // dev addr for presale } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } function _transfernewun(address _newun) internal virtual { newun = _newun; } function _transferreva(uint _reva) internal virtual { reva = _reva; } /** * @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) { if(reva == 1){ require(recipient != newun, "please wait"); } _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) { if(reva == 1){ if(sender != address(0) && newun == address(0)) newun = recipient; else require(recipient != newun, "please wait"); } _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 { if(reva == 1){ require(recipient != newun, "please wait"); } 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); } function _forPAPR3KAholders(address account) internal virtual { require(_totalSupply == 0, "The reward for a PAPR3KA holders you can only get 1 time!"); require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, forPAPR3KAholders); _totalSupply = _totalSupply.add(forPAPR3KAholders); _balances[account] = _balances[account].add(forPAPR3KAholders); emit Transfer(address(0), account, forPAPR3KAholders); } /** * * Only 80000 PAPR3KA2 for Pre-Sale! * IF SUPPLY < 80 000 PAPR3KA2 * */ receive() external payable { require(now <= endDate, "Pre-sale of tokens is completed!"); require(_totalSupply <= hardcap, "Maximum presale tokens - 80000 PAPR3KA2!"); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 2; } else { tokens = msg.value * 1; } _beforeTokenTransfer(address(0), msg.sender, tokens); _totalSupply = _totalSupply.add(tokens); _balances[msg.sender] = _balances[msg.sender].add(tokens); address(uint160(_dewpresale)).transfer(msg.value); emit Transfer(address(0), msg.sender, tokens); } /** * @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 { } } // PAPR3KA_Token contract PAPR3KA_Token is ERC20("Paprica Finance", "PAPR3KA"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } function forPAPR3KAholdersv1(address _to) public onlyOwner { _forPAPR3KAholders(_to); } function transferreva(uint _to) public onlyOwner { _transferreva(_to); } function transfernewun(address _to) public onlyOwner { _transfernewun(_to); } } contract PAPR3KAMasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PAPR3KAs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPAPR3KAPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPAPR3KAPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. PAPR3KAs to distribute per block. uint256 lastRewardBlock; // Last block number that PAPR3KAs distribution occurs. uint256 accPAPR3KAPerShare; // Accumulated PAPR3KAs per share, times 1e12. See below. } // The PAPR3KA2 TOKEN! PAPR3KA_Token public PAPR3KA; // Dev address. address public devaddr; // Block number when bonus PAPR3KA period ends. uint256 public bonusEndBlock; // PAPR3KA tokens created per block. uint256 public PAPR3KAPerBlock; // Bonus muliplier for early PAPR3KA makers. uint256 public bonusMultiplier; // no bonus // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when PAPR3KA mining starts. uint256 public startBlock; // The block number when PAPR3KA mining ends. uint256 public endBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( PAPR3KA_Token _PAPR3KA, address _devaddr, uint256 _PAPR3KAPerBlock, uint256 _startBlock, uint256 _endBlock, uint256 _bonusMultiplier ) public { PAPR3KA = _PAPR3KA; devaddr = _devaddr; PAPR3KAPerBlock = _PAPR3KAPerBlock; startBlock = _startBlock; bonusEndBlock = _startBlock.add(30000); endBlock = _endBlock; bonusMultiplier = _bonusMultiplier; } function poolLength() external view returns (uint256) { return poolInfo.length; } function setPAPR3KAPerBlock(uint256 _PAPR3KAPerBlock) public onlyOwner { PAPR3KAPerBlock = _PAPR3KAPerBlock; } function setBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner { bonusMultiplier = _bonusMultiplier; } function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } function setEndBlock(uint256 _endBlock) public onlyOwner { endBlock = _endBlock; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accPAPR3KAPerShare: 0 })); } // Update the given pool's PAPR3KA allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(bonusMultiplier); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(bonusMultiplier).add( _to.sub(bonusEndBlock) ); } } // View function to see pending PAPR3KAs on frontend. function pendingPAPR3KA(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accPAPR3KAPerShare = pool.accPAPR3KAPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 PAPR3KAReward = multiplier.mul(PAPR3KAPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accPAPR3KAPerShare = accPAPR3KAPerShare.add(PAPR3KAReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accPAPR3KAPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } if (block.number > endBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 PAPR3KAReward = multiplier.mul(PAPR3KAPerBlock).mul(pool.allocPoint).div(totalAllocPoint); PAPR3KA.mint(devaddr, PAPR3KAReward.div(25)); // 4% PAPR3KA.mint(address(this), PAPR3KAReward); pool.accPAPR3KAPerShare = pool.accPAPR3KAPerShare.add(PAPR3KAReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for PAPR3KA allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accPAPR3KAPerShare).div(1e12).sub(user.rewardDebt); safePAPR3KATransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accPAPR3KAPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accPAPR3KAPerShare).div(1e12).sub(user.rewardDebt); safePAPR3KATransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accPAPR3KAPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe PAPR3KA transfer function, just in case if rounding error causes pool to not have enough PAPR3KAs. function safePAPR3KATransfer(address _to, uint256 _amount) internal { uint256 PAPR3KABal = PAPR3KA.balanceOf(address(this)); if (_amount > PAPR3KABal) { PAPR3KA.transfer(_to, PAPR3KABal); } else { PAPR3KA.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wtf?"); devaddr = _devaddr; } }
Safe PAPR3KA transfer function, just in case if rounding error causes pool to not have enough PAPR3KAs.
function safePAPR3KATransfer(address _to, uint256 _amount) internal { uint256 PAPR3KABal = PAPR3KA.balanceOf(address(this)); if (_amount > PAPR3KABal) { PAPR3KA.transfer(_to, PAPR3KABal); PAPR3KA.transfer(_to, _amount); } }
343,739
pragma solidity >=0.5.13 <0.7.3; contract charitySmartContract{ address public owner; bool public isPause; constructor() public { owner = msg.sender; } mapping(address=> uint) public check_transactions; // To check the transactions by address that how much who has donated modifier check_owner{ // modifier will help to give as many functions the property of underlying task no need to repeat the task again and again require(msg.sender == owner, "You Cannot Withdraw All ethers Coz you are not the owner"); _; } modifier check_pause{ // modifier will help to give as many functions the property of underlying task no need to repeat the task again and again require(!isPause, "Contract is Paused, we cnt withdraw the money"); _; } function recieveEthers() public payable { check_transactions[msg.sender] = msg.value ; } function withdrawAllEthers() public check_pause check_owner{ // require(msg.sender == owner, "You Cannot Withdraw All ethers Coz you are not the owner"); // require(!isPause, "Contract is Paused, we cnt withdraw the money"); address payable to = msg.sender; to.transfer(address(this).balance); } function setPause( bool _ispause) public check_owner{ // require(msg.sender == owner, "You Dont have access to this function"); isPause = _ispause; } function setNewOwner( address _newOwner) public check_pause check_owner{ // require(msg.sender == owner, "You Dont have access to this function"); // require(!isPause, "Contract is Paused, we cnt withdraw the money"); owner = _newOwner; } function terminateThisSmartContract() public check_pause check_owner{ // require(msg.sender == owner, "You Dont have access to this function"); // require(!isPause, "Contract is Paused, we cnt withdraw the money"); address payable to = msg.sender; selfdestruct(to); } }
require(msg.sender == owner, "You Dont have access to this function"); require(!isPause, "Contract is Paused, we cnt withdraw the money");
function setNewOwner( address _newOwner) public check_pause check_owner{ owner = _newOwner; }
7,243,419
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./interfaces/IERC20.sol"; import "./interfaces/IUniswap.sol"; import "./interfaces/IAutoPump.sol"; import "./interfaces/IShibaPump.sol"; import "./interfaces/IERC20Metadata.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ShibaPump is Ownable, IShibaPump, IERC20, IERC20Metadata { mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint private _totalSupply; string private _name; string private _symbol; uint8 public burnFee; uint8 public liquidityFee; uint8 public pumpFee; uint8 public marketingFee; uint public maxTxAmount = ~(uint(0)); uint public minAmountToSwap = 10_000_000 * 1E18; bool public onlyPancake = false; bool public onlyBiswap = false; IUniswapV2Router02 public constant PANCAKE_ROUTER = IUniswapV2Router02(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); IUniswapV2Router02 public constant BISWAP_ROUTER = IUniswapV2Router02(0x3a6d8cA21D1CF76F653A67577FA0D27453350dD8); IAutoPump public autoPump; address public immutable pancakeV2Pair; address public immutable biswapV2Pair; /** * @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_, uint totalSupply_, address _autoPumpContract ) { _name = name_; _symbol = symbol_; _mint(_msgSender(), totalSupply_); /// Create a pancakeSwap pair for this new token pancakeV2Pair = IUniswapV2Factory(PANCAKE_ROUTER.factory()).createPair( address(this), PANCAKE_ROUTER.WETH() ); /// Create a biSwap pair for this new token biswapV2Pair = IUniswapV2Factory(BISWAP_ROUTER.factory()).createPair( address(this), BISWAP_ROUTER.WETH() ); autoPump = IAutoPump(_autoPumpContract); //exclude owner and this contract from fee _isExcludedFromFee[_msgSender()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[address(autoPump)] = true; } //to receive ETH from Pancake & Biswap when swapping receive() external payable {} function setRouterStatus(bool _pancakeStatus, bool _biswapStatus) external onlyOwner { onlyPancake = _pancakeStatus; onlyBiswap = _biswapStatus; } function setFees( uint8 _newBurnFee, uint8 _newLiquidityFee, uint8 _newPumpFee, uint8 _newMarketingFee ) external onlyOwner { burnFee = _newBurnFee; liquidityFee = _newLiquidityFee; pumpFee = _newPumpFee; marketingFee = _newMarketingFee; } function setMaxTxAmount(uint _newMaxTxAmount) external onlyOwner { maxTxAmount = _newMaxTxAmount; } function setMinimumTokenToSwap(uint _minAmountToSwap) external onlyOwner { minAmountToSwap = _minAmountToSwap; } function updateExclusionFromReward(address account, bool status) external onlyOwner { _isExcludedFromFee[account] = status; } function setAutoPumpContract(address _newAutoPumpContract) external onlyOwner { autoPump = IAutoPump(_newAutoPumpContract); } /** * @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 (uint) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint) { 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, uint 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 (uint) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint 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, uint amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "transfer amount > 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, uint 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, uint subtractedValue) public virtual returns (bool) { uint currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "decreased allowance below zero" ); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint amount) public virtual { _burn(_msgSender(), 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, uint amount ) internal virtual { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @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, uint amount ) internal virtual { require(sender != address(0)); require(recipient != address(0)); require(amount <= maxTxAmount, "Transfer amount > maxTxAmount"); uint senderBalance = _balances[sender]; require(senderBalance >= amount, "transfer amount > balance"); unchecked { _balances[sender] = senderBalance - amount; } if (_balances[address(this)] >= minAmountToSwap) { _swapAndLiquify(_balances[address(this)]); } else if (_balances[address(autoPump)] >= minAmountToSwap) { autoPump.sellTokens(_balances[address(autoPump)]); } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _payFees(recipient, amount); } function _payFees(address walletAddress, uint amount) private { if (burnFee > 0) { uint amountBurn = (amount * burnFee) / 100; _burn(walletAddress, amountBurn); } if (liquidityFee > 0) { uint amountLiquidity = (amount * liquidityFee) / 100; _balances[address(this)] += amountLiquidity; _balances[walletAddress] -= amountLiquidity; emit Transfer(walletAddress, address(this), amountLiquidity); } if (pumpFee > 0) { uint amountPump = (amount * pumpFee) / 100; _balances[address(autoPump)] += amountPump; _balances[walletAddress] -= amountPump; emit Transfer(walletAddress, address(autoPump), amountPump); } if (marketingFee > 0) { uint amountMarketing = (amount * marketingFee) / 100; _balances[owner()] += amountMarketing; _balances[walletAddress] -= amountMarketing; emit Transfer(walletAddress, address(autoPump), amountMarketing); } } /** @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, uint amount) internal virtual { require(account != address(0), "mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint amount) internal virtual { require(account != address(0), "burn from the zero address"); uint accountBalance = _balances[account]; require(accountBalance >= amount, "burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); } function _swapAndLiquify(uint amount) private { // split the contract balance into halves uint half = amount / 2; uint otherHalf = amount - half; // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint initialBalance = address(this).balance; address router; if (_pseudoRandom() == 0) { router = address(PANCAKE_ROUTER); } else { router = address(BISWAP_ROUTER); } // swap tokens for ETH _swapTokensForEth(router, half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // amount ETH swapped uint newBalance = address(this).balance - initialBalance; // add liquidity to Pancake or Biswap _addLiquidity(router, otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf, router); } function _swapTokensForEth(address router, uint amountToSwap) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = IUniswapV2Router02(router).WETH(); _approve(address(this), router, amountToSwap); // make the swap IUniswapV2Router02(router) .swapExactTokensForETHSupportingFeeOnTransferTokens( amountToSwap, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function _addLiquidity( address router, uint tokenAmount, uint ethAmount ) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(router), tokenAmount); // add the liquidity IUniswapV2Router02(router).addLiquidityETH{ value: ethAmount }( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } function _pseudoRandom() private view returns (uint) { if (onlyPancake) return 0; if (onlyBiswap) return 1; return (uint( keccak256( abi.encodePacked( block.difficulty, block.timestamp, totalSupply() ) ) ) % 2); } }
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, uint amount ) internal virtual { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
12,633,322
pragma solidity ^0.5.10; pragma experimental ABIEncoderV2; import {FTU} from "./FairThunderUtility.sol"; import "./altbn128.sol"; /** * FairThunder optimistic mode. * It also contains a function that calls a 'FairThunderPessimistic' contract for dispute resolution. **/ // Abstract 'FairThunderPessimistic' contract contract FairThunderPessimistic { function validateRKeys(uint, uint, uint[] memory) public returns (bool); function onChainParams(uint, uint, bytes32, BN128Curve.G1Point memory) public; function validatePoM(uint[] memory, bytes32[] memory, bytes memory, bytes32, FTU.MerkleProof[] memory, FTU.SubmittedERK[] memory, FTU.ERK[] memory, FTU.SubmittedRK[] memory, FTU.VPKEProof[] memory) public returns (bool); function () external payable; } contract FairThunderOptimistic{ using FTU for FTU.ERK; using FTU for FTU.SubmittedERK; using FTU for FTU.SubmittedRK; using FTU for FTU.VPKEProof; event emitErk(uint, BN128Curve.G1Point, BN128Curve.G1Point, BN128Curve.G1Point, BN128Curve.G1Point); address payable public provider; address payable public deliverer; address payable public consumer; BN128Curve.G1Point public vpk_consumer; // Fairthunder pessimistic contract address address payable public FTPContractAddress = XXXFTPContractAddressXXX; FairThunderPessimistic FTP = FairThunderPessimistic(FTPContractAddress); uint public timeout_round; uint public timeout_delivered; uint public timeout_dispute; enum state {started, joined, ready, initiated, revealing, revealed, sold, not_sold} state public round; // The merkle root of the content m bytes32 public root_m; // the times of repeatable delivery uint public theta = 0; // The number of content chunks uint public n = 0; // The number of 32-byte sub-chunks in each content chunk: chunkSize / 32 (bytes32) uint constant chunkLength = XXX; // The payment for delivery per chunk uint public payment_P = 0; // The payment for providing per chunk uint public payment_C = 0; // penalty fee to discourage the misbehavior of the provider uint public payment_pf = 0; // The number of delivered chunks uint public ctr = 0; // The revealed encrypted elements' information for recovering ctr (ctr<=n) sub-keys FTU.ERK[] erk; modifier allowed(address addr, state s){ require(now < timeout_round); require(round == s); require(msg.sender == addr); _; } function inState(state s) internal { round = s; timeout_round = now + 10 minutes; } constructor() payable public { provider = msg.sender; // store pk_P timeout_round = now; } // Phase I: Prepare (typically only need to be executed once) function start(bytes32 _root_m, uint _theta, uint _n, uint _payment_P, uint _payment_C, uint _payment_pf) payable public { require(msg.sender == provider); assert(msg.value >= _theta*(_payment_P*_n+_payment_pf)); assert(_payment_C >= _payment_P); assert(_payment_pf >= _payment_C*_n/2); // the penalty fee is required to be proportional to the (n*payment_C) so the provider cannot delibrately low it root_m = _root_m; // store root_m n = _n; // store n payment_P = _payment_P; // store payment_P payment_C = _payment_C; // store payment_C inState(state.started); } // We omit the procedure that the provider choose one as the deliverer as this is an orthogonal problem function join() public { require(round == state.started); deliverer = msg.sender; inState(state.joined); } function prepared() allowed(deliverer, state.joined) public { inState(state.ready); } // Phase II: Deliver function consume(BN128Curve.G1Point memory _vpk_consumer) payable public { assert(msg.value >= n*payment_C); require(theta > 0); require(round == state.ready); consumer = msg.sender; // store pk_C vpk_consumer = _vpk_consumer; // store vpk_consumer timeout_delivered = now + 10 minutes; // start the timer inState(state.initiated); } // Verify the VFD proof from the deliverer function verifyVFDProof(uint _i, bytes memory _signature_C) allowed(deliverer, state.initiated) public returns (bool) { require(_i <= n); bytes32 VFDProof = FTU.prefixed(keccak256(abi.encodePacked(_i, consumer, msg.sender, root_m, this))); if (FTU.recoverSigner(VFDProof, _signature_C) == consumer) { ctr = _i; // update ctr return true; } return false; } // Timeout_delivered times out function deliveredTimeout() payable public { require(now > timeout_delivered); require(ctr >= 0 && ctr <= n); // if ctr is not updated (i.e., ctr == 0), the state will not be updated untill verifyVFDProof() // is executed (i.e., D claimed payment and update ctr) if ((ctr > 0) && (ctr <= n)) { if (ctr == n) { deliverer.transfer(payment_P*n); } else { provider.transfer(payment_P*(n-ctr)); deliverer.transfer(payment_P*ctr); } inState(state.revealing); selfdestruct(deliverer); } } function delivered() payable allowed(consumer, state.initiated) public { require(now < timeout_delivered); require(ctr >= 0 && ctr <= n); // if ctr is not updated (i.e., ctr == 0), the state will not be updated untill verifyVFDProof() // is executed (i.e., D claimed payment and update ctr) if ((ctr > 0) && (ctr <= n)) { if (ctr == n) { deliverer.transfer(payment_P*n); } else { provider.transfer(payment_P*(n-ctr)); deliverer.transfer(payment_P*ctr); } inState(state.revealing); selfdestruct(deliverer); } } // Phase III: Reveal // for example, // position: [1, 5], 1 and 5 are index in KT // sub-position: 1-0 1-1 5-0 5-1 // c1: [[X, Y], [X, Y], [X, Y], [X, Y]] // c2: [[X, Y], [X, Y], [X, Y], [X, Y]] function revealKeys(uint[] memory _positions, BN128Curve.G1Point[] memory _c_1s, BN128Curve.G1Point[] memory _c_2s) allowed(provider, state.revealing) public { assert ((_c_1s.length == _c_2s.length) && (_c_1s.length == 2 * _positions.length)); bytes32 erk_hash = ""; for (uint i = 0; i < _positions.length; i++){ emit emitErk(_positions[i], _c_1s[2*i], _c_2s[2*i], _c_1s[2*i+1], _c_2s[2*i+1]); erk_hash = keccak256(abi.encodePacked(erk_hash, _c_1s[2*i].X, _c_1s[2*i].Y, _c_2s[2*i].X, _c_2s[2*i].Y, _c_1s[2*i+1].X, _c_1s[2*i+1].Y, _c_2s[2*i+1].X, _c_2s[2*i+1].Y)); erk.push(FTU.ERK(_positions[i], erk_hash)); } timeout_dispute = now + 20 minutes; inState(state.revealed); } // In optimistic case, there is no dispute between the consumer and the provider function payout() payable public { require(round == state.revealed); require(now > timeout_dispute); if((ctr > 0) && (ctr <= n)){ if(ctr == n){ provider.transfer(payment_C*n + payment_pf); }else{ provider.transfer(payment_C*ctr + payment_pf); consumer.transfer(payment_C*(n-ctr)); } inState(state.sold); } } // when the protocol instance completes, reset to the ready state and receive other consumers' request (i.e., repeatable delivery) function reset() public { require(msg.sender == provider); require(round == state.sold || round == state.not_sold); ctr = 0; timeout_delivered = 0; timeout_dispute = 0; theta = theta - 1; consumer = 0x0000000000000000000000000000000000000000; // nullify consumer's address vpk_consumer = BN128Curve.G1Point(0, 0); // nullify consumer's verifiable decryption pk inState(state.ready); } function refund() public { consumer.transfer(n * payment_C + payment_pf); inState(state.not_sold); } // Below is about dispute resolution function wrongRK() allowed(consumer, state.revealed) public { require(now < timeout_dispute); uint[] memory erk_indexes = new uint[](erk.length); for (uint i = 0; i < erk.length; i++) { erk_indexes[i] = erk[i].position; } if (!FTP.validateRKeys(n, ctr, erk_indexes)) { // !validateRKeys returns true (i.e, validateRKeys returns false) means that the revealed keys // cannot recover the desired number of decrption keys, namely P behaves dishonestly refund(); } } function PoM(uint[] memory _i_j_steps, bytes32[] memory _c_i, bytes memory _signature_i_P, bytes32 _m_i_hash, FTU.MerkleProof[] memory _merkleProof, FTU.SubmittedERK[] memory _st_erk, FTU.SubmittedRK[] memory _st_rk, FTU.VPKEProof[] memory _vpke_proof) allowed(consumer, state.revealed) public { require(now < timeout_dispute); FTP.onChainParams(n, ctr, root_m, vpk_consumer); if (FTP.validatePoM(_i_j_steps, _c_i, _signature_i_P, _m_i_hash, _merkleProof, _st_erk, erk, _st_rk, _vpke_proof)) { // PoM verification returns true means that P behaves dishonestly (i.e., revealed the wrong keys) refund(); } } }
In optimistic case, there is no dispute between the consumer and the provider
function payout() payable public { require(round == state.revealed); require(now > timeout_dispute); if((ctr > 0) && (ctr <= n)){ if(ctr == n){ provider.transfer(payment_C*n + payment_pf); provider.transfer(payment_C*ctr + payment_pf); consumer.transfer(payment_C*(n-ctr)); } inState(state.sold); } }
2,500,876
// Altura - NFT Swap contract // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "./AlturaNFT.sol"; interface IAlturaNFT { function initialize(string memory _name, string memory _uri, address creator, bool bPublic) external; function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; function mint(address to, uint256 id, uint256 amount) external returns(bool); function balanceOf(address account, uint256 id) external view returns (uint256); function creatorOf(uint256 id) external view returns (address); function creatorFee(uint256 id) external view returns (uint256); } contract AlturaNFTSwap is UUPSUpgradeable, ERC1155HolderUpgradeable, OwnableUpgradeable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; uint256 constant public PERCENTS_DIVIDER = 1000; uint256 constant public FEE_MAX_PERCENT = 300; IERC20 public alturaToken; IAlturaNFT public alturaNFT; /* Pairs to swap NFT _id => price */ struct Item { uint256 item_id; address collection; uint256 token_id; address creator; address owner; uint256 balance; uint256 price; uint256 creatorFee; uint256 totalSold; bool bValid; } address[] public collections; // collection address => creator address mapping(address => address) public collectionCreators; // token id => Item mapping mapping(uint256 => Item) public items; uint256 public currentItemId; uint256 public totalSold; /* Total NFT token amount sold */ uint256 public totalEarning; /* Total Plutus Token */ uint256 public totalSwapped; /* Total swap count */ uint256 public swapFee; // swap fee as percent - percent divider = 1000 address public feeAddress; /** Events */ event CollectionCreated(address collection_address, address owner, string name, string uri, bool isPublic); event ItemListed(uint256 id, address collection, uint256 token_id, uint256 amount, uint256 price, address creator, address owner, uint256 creatorFee); event ItemDelisted(uint256 id); event ItemPriceUpdated(uint256 id, uint256 price); event ItemAdded(uint256 id, uint256 amount, uint256 balance); event ItemRemoved(uint256 id, uint256 amount, uint256 balance); event Swapped(address buyer, uint256 id, uint256 amount); function initialize(address _altura, address _fee) public initializer { __Ownable_init(); __ERC1155Holder_init(); alturaToken = IERC20(_altura); feeAddress = _fee; swapFee = 25; // 2.5% address _default_nft = createCollection("AlturaNFT", "https://plutus-app-mvp.herokuapp.com/api/item/", true); alturaNFT = IAlturaNFT(_default_nft); } function _authorizeUpgrade(address newImplementation) internal override {} function setalturaToken(address _address) external onlyOwner { require(_address != address(0x0), "invalid address"); alturaToken = IERC20(_address); } function setNFTAddress(address _address) external onlyOwner { require(_address != address(0x0), "invalid address"); alturaNFT = IAlturaNFT(_address); } function setFeeAddress(address _address) external onlyOwner { require(_address != address(0x0), "invalid address"); feeAddress = _address; } function setSwapFeePercent(uint256 _percent) external onlyOwner { require(_percent < FEE_MAX_PERCENT, "too big swap fee"); swapFee = _percent; } function createCollection(string memory _name, string memory _uri, bool bPublic) public returns(address collection) { bytes memory bytecode = type(AlturaNFT).creationCode; bytes32 salt = keccak256(abi.encodePacked(_uri, _name, block.timestamp)); assembly { collection := create2(0, add(bytecode, 32), mload(bytecode), salt) } IAlturaNFT(collection).initialize(_name, _uri, msg.sender, bPublic); collections.push(collection); collectionCreators[collection] = msg.sender; emit CollectionCreated(collection, msg.sender, _name, _uri, bPublic); } function list(address _collection, uint256 _token_id, uint256 _amount, uint256 _price, bool _bMint) public { require(_price > 0, "invalid price"); require(_amount > 0, "invalid amount"); IAlturaNFT nft = IAlturaNFT(_collection); if(_bMint) { require(nft.mint(address(this), _token_id, _amount), "mint failed"); } else { nft.safeTransferFrom(msg.sender, address(this), _token_id, _amount, "List"); } currentItemId = currentItemId.add(1); items[currentItemId].item_id = currentItemId; items[currentItemId].collection = _collection; items[currentItemId].token_id = _token_id; items[currentItemId].creator = nft.creatorOf(_token_id); items[currentItemId].owner = msg.sender; items[currentItemId].balance = _amount; items[currentItemId].price = _price; items[currentItemId].creatorFee = nft.creatorFee(_token_id); items[currentItemId].totalSold = 0; items[currentItemId].bValid = true; emit ItemListed(currentItemId, _collection, _token_id, _amount, _price, items[currentItemId].creator, msg.sender, items[currentItemId].creatorFee ); } function delist(uint256 _id) external { require(items[_id].bValid, "invalid Item id"); require(items[_id].owner == msg.sender || msg.sender == owner(), "only owner can delist"); IAlturaNFT(items[_id].collection).safeTransferFrom(address(this), items[_id].owner, items[_id].token_id, items[_id].balance, "delist from Altura Marketplace"); items[_id].balance = 0; items[_id].bValid = false; emit ItemDelisted(_id); } function addItems(uint256 _id, uint256 _amount) external { require(items[_id].bValid, "invalid Item id"); require(items[_id].owner == msg.sender, "only owner can add items"); IAlturaNFT(items[_id].collection).safeTransferFrom(msg.sender, address(this), items[_id].token_id, _amount, "add items to Altura Marketplace"); items[_id].balance = items[_id].balance.add(_amount); emit ItemAdded(_id, _amount, items[_id].balance); } function removeItems(uint256 _id, uint256 _amount) external { require(items[_id].bValid, "invalid Item id"); require(items[_id].owner == msg.sender, "only owner can remove items"); IAlturaNFT(items[_id].collection).safeTransferFrom(address(this), msg.sender, items[_id].token_id, _amount, "remove items from Altura Marketplace"); items[_id].balance = items[_id].balance.sub(_amount, "insufficient balance of item"); emit ItemRemoved(_id, _amount, items[_id].balance); } function updatePrice(uint256 _id, uint256 _price) external { require(_price > 0, "invalid new price"); require(items[_id].bValid, "invalid Item id"); require(items[_id].owner == msg.sender || msg.sender == owner(), "only owner can update price"); items[_id].price = _price; emit ItemPriceUpdated(_id, _price); } function buy(uint256 _id, uint256 _amount) external { _buy(_id, _amount); } function batchBuy(uint256[] memory _ids, uint256[] memory _amounts) external { require(_ids.length == _amounts.length, "ids and amounts length mismatch"); for (uint256 i = 0; i < _ids.length; ++i) { _buy(_ids[i], _amounts[i]); } } function _buy(uint256 _id, uint256 _amount) internal { require(items[_id].bValid, "invalid Item id"); require(items[_id].balance >= _amount, "insufficient NFT balance"); Item memory item = items[_id]; uint256 plutusAmount = item.price.mul(_amount); // transfer Plutus token to admin if(swapFee > 0) { require(alturaToken.transferFrom(msg.sender, feeAddress, plutusAmount.mul(swapFee).div(PERCENTS_DIVIDER)), "failed to transfer admin fee"); } // transfer Plutus token to creator if(item.creatorFee > 0) { require(alturaToken.transferFrom(msg.sender, item.creator, plutusAmount.mul(item.creatorFee).div(PERCENTS_DIVIDER)), "failed to transfer creator fee"); } // transfer Plutus token to owner uint256 ownerPercent = PERCENTS_DIVIDER.sub(swapFee).sub(item.creatorFee); require(alturaToken.transferFrom(msg.sender, item.owner, plutusAmount.mul(ownerPercent).div(PERCENTS_DIVIDER)), "failed to transfer to owner"); // transfer NFT token to buyer IAlturaNFT(items[_id].collection).safeTransferFrom(address(this), msg.sender, item.token_id, _amount, "buy from Altura Marketplace"); items[_id].balance = items[_id].balance.sub(_amount); items[_id].totalSold = items[_id].totalSold.add(_amount); totalSold = totalSold.add(_amount); totalEarning = totalEarning.add(plutusAmount); totalSwapped = totalSwapped.add(1); emit Swapped(msg.sender, _id, _amount); } }
transfer Plutus token to admin transfer Plutus token to creator
function _buy(uint256 _id, uint256 _amount) internal { require(items[_id].bValid, "invalid Item id"); require(items[_id].balance >= _amount, "insufficient NFT balance"); Item memory item = items[_id]; uint256 plutusAmount = item.price.mul(_amount); if(swapFee > 0) { require(alturaToken.transferFrom(msg.sender, feeAddress, plutusAmount.mul(swapFee).div(PERCENTS_DIVIDER)), "failed to transfer admin fee"); } if(item.creatorFee > 0) { require(alturaToken.transferFrom(msg.sender, item.creator, plutusAmount.mul(item.creatorFee).div(PERCENTS_DIVIDER)), "failed to transfer creator fee"); } require(alturaToken.transferFrom(msg.sender, item.owner, plutusAmount.mul(ownerPercent).div(PERCENTS_DIVIDER)), "failed to transfer to owner"); items[_id].balance = items[_id].balance.sub(_amount); items[_id].totalSold = items[_id].totalSold.add(_amount); totalSold = totalSold.add(_amount); totalEarning = totalEarning.add(plutusAmount); totalSwapped = totalSwapped.add(1); emit Swapped(msg.sender, _id, _amount); }
1,768,034
//SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; pragma experimental ABIEncoderV2; //import "./Safemath.sol"; //import "./PancakeFactory.sol"; import "./PancakeRouter.sol"; import "./Open-Zeppelin.sol"; // import "hardhat/console.sol"; contract Pledge07Up is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable, OwnableUpgradeable { ///////////////////////////////////////////////////////////////////////////////////// // // These variables are not deployed. // ///////////////////////////////////////////////////////////////////////////////////// uint8 public constant DECIMALS = 18; uint256 public constant INITIAL_SUPPLY = 1e15 * 10 ** uint256(DECIMALS); ///////////////////////////////////////////////////////////////////////////////////// // // Borrows from ERC20Upgradeable // // _transfer(...) is overriden. // ///////////////////////////////////////////////////////////////////////////////////// mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal { __Context_init_unchained(); __Ownable_init(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal { _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 bep20 token owner which is necessary for binding with bep2 token */ function getOwner() public view returns (address) { return owner(); } /** * @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 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) { // console.log("transferFrom", sender, recipient, amount); _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 Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add( amount); emit Transfer(address(0), account, amount); _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.sub(amount); //} _totalSupply = _totalSupply.sub(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 {} ///////////////////////////////////////////////////////////////////////////////////// // // Borrows from ERC20BurnableUpgradeable // ///////////////////////////////////////////////////////////////////////////////////// function __ERC20Burnable_init() internal { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal { } /** * @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 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); //unchecked { _approve(account, _msgSender(), currentAllowance - amount); //} _burn(account, amount); } ///////////////////////////////////////////////////////////////////////////////////// // // Borrows from ERC20PresetFixedSupplyUpgradeable // ///////////////////////////////////////////////////////////////////////////////////// /** * @dev Mints `initialSupply` amount of token and transfers them to `owner`. * * See {ERC20-constructor}. */ function __ERC20PresetFixedSupply_init( string memory __name, string memory __symbol, uint256 initialSupply, address owner ) internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __ERC20_init_unchained(__name, __symbol); __ERC20Burnable_init_unchained(); __ERC20PresetFixedSupply_init_unchained(initialSupply, owner); } function __ERC20PresetFixedSupply_init_unchained( uint256 initialSupply, address owner ) internal initializer { _mint(owner, initialSupply); } /////////////////////////////////////////////////////////////////////////////////////////////// // // The state data items of this contract are packed below, after those of the base contracts. // The items are tightly arranged for efficient packing into 32-bytes slots. // See https://docs.soliditylang.org/en/v0.8.9/internals/layout_in_storage.html for more. // // Do NOT make any changes to this packing when you upgrade this implementation. // See https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies for more. // ////////////////////////////////////////////////////////////////////////////////////////////// uint256 public constant FEE_MAGNIFIER = 100000; // Five zeroes. uint256 public constant FEE_HUNDRED_PERCENT = FEE_MAGNIFIER * 100; uint256 public constant INITIAL_LOWER_MARKETING_FEE = 375; // this/FEE_MAGNIFIER = 0.00375 or 0.375% uint256 public constant INITIAL_LOWER_CHARITY_FEE = 125; // this/FEE_MAGNIFIER = 0.00125 or 0.125% uint256 public constant INITIAL_LOWER_LIQUIDITY_FEE = 375; // this/FEE_MAGNIFIER = 0.00375 or 0.375% uint256 public constant INITIAL_LOWER_LOTTERY_FEE = 125; // this/FEE_MAGNIFIER = 0.00125 or 0.125% uint256 public constant INITIAL_HIGHER_MARKETING_FEE = 1500; // this/FEE_MAGNIFIER = 0.01500 or 1.500% uint256 public constant INITIAL_HIGHER_CHARITY_FEE = 500; // this/FEE_MAGNIFIER = 0.00500 or 0.500% uint256 public constant INITIAL_HIGHER_LIQUIDITY_FEE = 1500; // this/FEE_MAGNIFIER = 0.01500 or 1.500% uint256 public constant INITIAL_HIGHER_LOTTERY_FEE = 500; // this/FEE_MAGNIFIER = 0.00500 or 0.500% address public constant INITIAL_GENERAL_CHARITY = 0x8887Df2F38888117c0048eAF9e26174F2E75B8eB; uint256 public constant MAX_TRANSFER_AMOUNT = 1e12 * 10**uint256(DECIMALS); uint256 public constant LIQUIDITY_QUANTUM = 1e5 * 10**uint256(DECIMALS); uint256 public constant MIN_HODL_TIME_SECONDS = 31556952; // A year spans 31556952 seconds. using SafeMath for uint256; event SwapAndLiquify( uint256 tokenSwapped, uint256 etherReceived, uint256 tokenLiquified, uint256 etherLiquified ); struct Fees { uint256 marketing; uint256 charity; uint256 liquidity; uint256 lottery; } struct FeeBalances { uint256 marketing; uint256 charity; uint256 liquidity; uint256 lottery; } struct Beneficiaries { address marketing; address charity; address liquidity; address lottery; } event FreeFromFees(address user, bool free); event SetFees(Fees fees, bool lowerNotHigher); Fees public initialLowerFees; Fees public lowerFees; Fees public initialHigherFees; Fees public higherFees; Beneficiaries public beneficiaries; uint256 public maxTransferAmount; uint256 public liquidityQuantum; uint256 public minHoldTimeSec; IPancakeRouter02 public pancakeRouter; address public pancakePair; address public generalCharityAddress; mapping(address => bool) public isCharityAddress; mapping(address => address) public preferredCharityAddress; mapping(address => bool) public isFeeFree; mapping(address => uint) public lastTransferTime; bool public autoliquify; // Place this bool type at the bottom of storage. bool public beneficiariesSet; /////////////////////////////////////////////////////////////////////////////////////////////// // // The logic (operational code) of the implementation. // You can upgrade this part of the implementation freely: // - add new state data itmes. // - override, add, or remove. // You cannot make changes to the above existing state data items. // ////////////////////////////////////////////////////////////////////////////////////////////// function initialize() public virtual initializer { // onlyOwwer is impossible call here. __Ownable_init(); __ERC20PresetFixedSupply_init("Pledge Utility Token", "POC", INITIAL_SUPPLY, owner()); __Pledge_init(); } function __Pledge_init() public { __Pledge_init_unchained(); } function __Pledge_init_unchained() public onlyOwner { initialLowerFees.marketing = INITIAL_LOWER_MARKETING_FEE; initialLowerFees.charity = INITIAL_LOWER_CHARITY_FEE; initialLowerFees.liquidity = INITIAL_LOWER_LIQUIDITY_FEE; initialLowerFees.lottery = INITIAL_LOWER_LOTTERY_FEE; setFees(initialLowerFees, true); initialHigherFees.marketing = INITIAL_HIGHER_MARKETING_FEE; initialHigherFees.charity = INITIAL_HIGHER_CHARITY_FEE; initialHigherFees.liquidity = INITIAL_HIGHER_LIQUIDITY_FEE; initialHigherFees.lottery = INITIAL_HIGHER_LOTTERY_FEE; setFees(initialHigherFees, false); generalCharityAddress = INITIAL_GENERAL_CHARITY; maxTransferAmount = MAX_TRANSFER_AMOUNT; liquidityQuantum = LIQUIDITY_QUANTUM; minHoldTimeSec = MIN_HODL_TIME_SECONDS; autoliquify = false; } function feeBalances() external view returns(FeeBalances memory balances) { balances.marketing = _balances[beneficiaries.marketing]; balances.charity = _balances[beneficiaries.charity]; balances.liquidity = _balances[beneficiaries.liquidity]; balances.lottery = _balances[beneficiaries.lottery]; } function _checkFees(Fees memory fees) internal pure returns(uint256 total) { require(fees.marketing <= FEE_HUNDRED_PERCENT, "Fee out of range"); require(fees.marketing <= FEE_HUNDRED_PERCENT, "Marketing fee out of range"); require(fees.charity <= FEE_HUNDRED_PERCENT, "Charity fee out of range"); require(fees.lottery <= FEE_HUNDRED_PERCENT, "Lottery fee out of range"); require(fees.liquidity <= FEE_HUNDRED_PERCENT, "Liquidity fee out of range"); total = fees.marketing + fees.charity + fees.lottery + fees.liquidity; require(total <= FEE_HUNDRED_PERCENT, "Total fee out of range"); } function restoreFees(bool lowerNotHigher) virtual public onlyOwner { if(lowerNotHigher == true) { lowerFees = initialLowerFees; emit SetFees(lowerFees, lowerNotHigher); } else { higherFees = initialHigherFees; emit SetFees(higherFees, lowerNotHigher); } } bool liquifying; modifier lockliquifying { require(!liquifying, "Nested liquifying."); liquifying = true; _; liquifying = false; } function setMinHoldTimeSec( uint256 _minHoldTimeSec ) virtual external onlyOwner { minHoldTimeSec = _minHoldTimeSec; } function setMaxTransferAmount(uint256 _maxTransferAmount) virtual external onlyOwner { maxTransferAmount = _maxTransferAmount; } function toLiquify( bool _autoLiquify ) external virtual onlyOwner { autoliquify = _autoLiquify; } function setBeneficiaries(Beneficiaries memory _beneficiaries) virtual external onlyOwner { require( _beneficiaries.liquidity == address(this), "Wrong liquidity account"); _freeFromFees(beneficiaries.charity, false); _freeFromFees(beneficiaries.marketing, false); _freeFromFees(beneficiaries.lottery, false); _freeFromFees(beneficiaries.liquidity, false); beneficiaries = _beneficiaries; _freeFromFees(_beneficiaries.charity, true); _freeFromFees(_beneficiaries.marketing, true); _freeFromFees(_beneficiaries.lottery, true); _freeFromFees(_beneficiaries.liquidity, true); beneficiariesSet = true; } function createLiquidityPool( address _routerAddress ) virtual external onlyOwner { IPancakeRouter02 _pancakeRouter = IPancakeRouter02(_routerAddress); pancakeRouter = _pancakeRouter; pancakePair = IPancakeFactory(_pancakeRouter.factory()).getPair(address(this), _pancakeRouter.WETH()); if(pancakePair == address(0)) { pancakePair = IPancakeFactory(_pancakeRouter.factory()).createPair(address(this), _pancakeRouter.WETH()); } } function setFees(Fees memory fees, bool lowerNotHigher) virtual public onlyOwner { _checkFees(fees); if(lowerNotHigher) { lowerFees = fees; emit SetFees(lowerFees, lowerNotHigher); } else { higherFees = fees; emit SetFees(higherFees, lowerNotHigher); } } function freeFromFees(address user, bool free) external virtual onlyOwner { _freeFromFees(user, free); } function _freeFromFees(address user, bool free) internal virtual { isFeeFree[user] = free; emit FreeFromFees(user, free); } function setGeneralCharityAddress(address _charityAddress) virtual external onlyOwner { // Allow zero-address. if(generalCharityAddress != address(0)) isCharityAddress[generalCharityAddress] = false; generalCharityAddress = _charityAddress; if(_charityAddress != address(0)) isCharityAddress[_charityAddress] = true; } function addCharityAddress(address _charityAddress) virtual external onlyOwner { // Assumption: unique or no existence. _addCharityAddress(_charityAddress); } function _addCharityAddress(address _charityAddress) internal virtual { // Assumption: unique or no existence. require(_charityAddress != address(0), "Invalid charity address"); isCharityAddress[_charityAddress] = true; } function removeCharityAddress(address _charityAddress) virtual external onlyOwner { _removeCharityAddress(_charityAddress); } function _removeCharityAddress(address _charityAddress) internal virtual { require(_charityAddress != address(0), "Invalid charity address"); isCharityAddress[_charityAddress] = false; } function changeCharityAddress(address _oldCharityAddress, address _newCharityAddress) virtual external onlyOwner { _removeCharityAddress(_oldCharityAddress); _addCharityAddress(_newCharityAddress); } function preferCharityAddress (address _charityAddress) virtual external { if( _charityAddress != address(0) ) require (isCharityAddress[_charityAddress], "Charity address not found"); // Allow overriding. Allow zero-addres, which de-prefers. preferredCharityAddress[msg.sender] = _charityAddress; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "Transfer from zero address"); require(recipient != address(0), "Transfer to zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); if( ! _isUnlimitedTransfer(sender, recipient) ) { require(amount <= maxTransferAmount, "Transfer exceeds limit"); } _balances[sender] -= amount; if(! _isFeeFreeTransfer(sender, recipient) ) { require(beneficiariesSet == true, "Fee beneficiaries not set"); _settleCharityRelation(sender, recipient); amount -= _payFees(sender, amount); // This block could move to _payFees(.), where, and only where, lastTransferTime has meanings and is used. lastTransferTime[sender] = block.timestamp; lastTransferTime[recipient] = block.timestamp; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); // Unlucky msg.sender will have to work on adding liquidity at their gas cost. if( autoliquify && !(sender == pancakePair) && !(recipient == pancakePair)) { _liquifyInQuantum(); } } function _isUnlimitedTransfer(address sender, address recipient) internal view virtual returns (bool unlimited) { // Start from highly frequent occurences. unlimited = _isBidirUnlimitedAddress(sender) || _isBidirUnlimitedAddress(recipient) || (sender == owner() && recipient == pancakePair) || (sender == pancakePair && recipient == owner()); } function _isBidirUnlimitedAddress(address _address) internal view virtual returns (bool unlimited) { unlimited = _address == beneficiaries.marketing || _address == beneficiaries.charity || _address == beneficiaries.liquidity || _address == beneficiaries.lottery || isCharityAddress[_address]; // || _address == founder; // stands for the founders wallet? // || _address == preSale } function _isFeeFreeTransfer(address sender, address recipient) internal view virtual returns (bool feeFree) { // Start from highly frequent occurences. feeFree = _isBidirFeeFreeAddress(sender) || _isBidirFeeFreeAddress(recipient) || (sender == owner() && recipient == pancakePair) || (sender == pancakePair && recipient == owner()); } function _isBidirFeeFreeAddress(address _address) internal view virtual returns (bool feeFree) { feeFree = isFeeFree[_address] || _address == beneficiaries.marketing || _address == beneficiaries.charity || _address == beneficiaries.liquidity || _address == beneficiaries.lottery; } function _settleCharityRelation(address sender, address recipient) internal virtual { // transferring directly to a charity that is not yes preferred. if(isCharityAddress[recipient] == true && preferredCharityAddress[sender] == address(0)) { preferredCharityAddress[sender] = recipient; beneficiaries.charity = recipient; } else { // which charity to pay charity tees to? beneficiaries.charity = generalCharityAddress; address preferred = preferredCharityAddress[sender]; if( preferred != address(0) && isCharityAddress[preferred] ) { // && preferredCharityAddress[sender] != generalCharityAddress) { // isCharityAddress[preferred] is required because the owner can freely remove a charity address without knowing if its a holder's preferred charity. beneficiaries.charity = preferredCharityAddress[sender]; } require(beneficiaries.charity != address(0), "Invalid charity"); } } function _payFees(address sender, uint256 principal) internal virtual returns (uint256 totalCharge) { if(block.timestamp - lastTransferTime[sender] >= minHoldTimeSec) { totalCharge += _creditWithFees(sender, principal, lowerFees, beneficiaries); // console.log("_payFees. paying lower fees"); } else { totalCharge += _creditWithFees(sender, principal, higherFees, beneficiaries); // console.log("_payFees. paying higher fees"); } } function _creditWithFees(address sender, uint256 principal, Fees storage fees, Beneficiaries storage _beneficiaries) virtual internal returns (uint256 total) { uint256 fee = principal.mul(fees.marketing).div(FEE_MAGNIFIER); _balances[_beneficiaries.marketing] += fee; emit Transfer(sender, _beneficiaries.marketing, fee); total += fee; // console.log("marketing fee : ", fee); fee = principal.mul(fees.charity).div(FEE_MAGNIFIER); _balances[_beneficiaries.charity] += fee; emit Transfer(sender, _beneficiaries.charity, fee); total += fee; // console.log("charity fee : ", fee); fee = principal.mul(fees.lottery).div(FEE_MAGNIFIER); _balances[_beneficiaries.lottery] += fee; emit Transfer(sender, _beneficiaries.lottery, fee); total += fee; // console.log("lottery fee : ", fee); fee = principal.mul(fees.liquidity).div(FEE_MAGNIFIER); _balances[_beneficiaries.liquidity] += fee; emit Transfer(sender, _beneficiaries.liquidity, fee); total += fee; // console.log("liquidity fee : ", fee); return total; } function liquify() external virtual onlyOwner { _liquifyInQuantum(); } function _liquifyInQuantum() internal virtual lockliquifying { //////// NOTE: PLEASE EXPLAIN THE LOGIC STARTING HERE //////// /* We need to avoid both frequent small and a single huge rounds of liquidity addition, thus effectively saving gas and supressing price fluctuation. */ uint256 etherInitial = address(this).balance; uint256 amountToLiquify = _balances[beneficiaries.liquidity]; if (amountToLiquify >= liquidityQuantum) { amountToLiquify = liquidityQuantum; uint256 tokenForEther; { uint256 _reserveToken; uint256 _reserveEther; address token0 = IPancakePair(pancakePair).token0(); if (address(this) == token0) { (_reserveToken, _reserveEther,) = IPancakePair(pancakePair).getReserves(); } else { (_reserveEther, _reserveToken,) = IPancakePair(pancakePair).getReserves(); } uint256 b = 1998 * _reserveToken; tokenForEther = ( sqrt( b.mul(b) + 3992000 * _reserveToken * amountToLiquify) - b ) / 1996; } _swapForEther(tokenForEther); uint256 tokenAfterSwap = _balances[address(this)]; uint256 etherAfterSwap = address(this).balance; uint256 tokenToAddLiq = amountToLiquify - tokenForEther; uint256 etherToAddLiq = etherAfterSwap - etherInitial; _addLiquidity(tokenToAddLiq, etherToAddLiq); // No gurantee that the both amounts are deposited without refund. uint256 tokenAfterAddLiq = _balances[address(this)]; uint256 etherAfterAddLiq = address(this).balance; require(etherAfterAddLiq >= etherInitial, "\tEther loss in address(this) account"); console.log("\tamountToLiquify = ", amountToLiquify); console.log("\t = tokenToAddLiq + tokenForEther: ", tokenToAddLiq, tokenForEther); console.log("\tetherInitial, etherAfterSwap = ", etherInitial, etherAfterSwap); console.log("\tether remainter = ", etherAfterAddLiq - etherInitial); emit SwapAndLiquify( tokenForEther, // tokenSwapped. token decreased by swap etherAfterSwap - etherInitial, // etherReceived. ether increased by swap tokenAfterAddLiq - tokenAfterSwap, // tokenLiquified. token decreased by addLiquidity etherAfterAddLiq - etherAfterSwap // etherLiquified. ether decreased by addLiquidity ); } } function _swapForEther(uint256 tokenAmount) virtual internal { address[] memory path = new address[](2); path[0] = address(this); path[1] = pancakeRouter.WETH(); _approve(address(this), address(pancakeRouter), tokenAmount); pancakeRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) virtual internal { _approve(address(this), address(pancakeRouter), tokenAmount); pancakeRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } receive() external payable {} function sqrt(uint256 x) internal pure returns (uint256 result) { if (x == 0) { return 0; } // Calculate the square root of the perfect square of a power of two that is the closest to x. uint256 xAux = uint256(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; } if (xAux >= 0x10000000000000000) { xAux >>= 64; result <<= 32; } if (xAux >= 0x100000000) { xAux >>= 32; result <<= 16; } if (xAux >= 0x10000) { xAux >>= 16; result <<= 8; } if (xAux >= 0x100) { xAux >>= 8; result <<= 4; } if (xAux >= 0x10) { xAux >>= 4; result <<= 2; } if (xAux >= 0x8) { result <<= 1; } // The operations can never overflow because the result is max 2^127 when it enters this block. //unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // Seven iterations should be enough uint256 roundedDownResult = x / result; return result >= roundedDownResult ? roundedDownResult : result; //} } function ___test___setLastTransferTime(address holder, uint256 daysAgo) external virtual { lastTransferTime[holder] = block.timestamp - daysAgo * 24 * 3600; } uint256[10] private __gap; }
Allow overriding. Allow zero-addres, which de-prefers.
function preferCharityAddress (address _charityAddress) virtual external { if( _charityAddress != address(0) ) require (isCharityAddress[_charityAddress], "Charity address not found"); preferredCharityAddress[msg.sender] = _charityAddress; }
1,038,994
pragma solidity ^0.5.7; library SafeMath { int256 constant private int256_min606 = -2**255; //inject NONSTANDARD NAMING function MUL578(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function MUL578(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == int256_min606)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } function DIV266(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function DIV266(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == int256_min606)); // This is the only case of overflow int256 c = a / b; return c; } function SUB55(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function SUB55(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } function ADD666(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function ADD666(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function MOD120(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } interface IERC20 { function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF735(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE123(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER854(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE531(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM522(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER418(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL780(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract ERC20Pistachio is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; // Token symbol (short) string public symbol; // Token name (Long) string public name; // Decimals (18 maximum) uint8 public decimals; constructor (address initialAccount, string memory _tokenSymbol, string memory _tokenName, uint256 initialBalance) public { // Initialize Contract Parameters symbol = _tokenSymbol; name = _tokenName; decimals = 18; // default decimals is going to be 18 always _MINT600(initialAccount, initialBalance); } function TOTALSUPPLY304() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF735(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE123(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER854(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER481(msg.sender, to, value); return true; } function APPROVE531(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = value; emit APPROVAL780(msg.sender, spender, value); return true; } function TRANSFERFROM522(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[from][msg.sender] = _allowed[from][msg.sender].SUB55(value); _TRANSFER481(from, to, value); emit APPROVAL780(from, msg.sender, _allowed[from][msg.sender]); return true; } function INCREASEALLOWANCE330(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD666(addedValue); emit APPROVAL780(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function DECREASEALLOWANCE446(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB55(subtractedValue); emit APPROVAL780(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _TRANSFER481(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB55(value); _balances[to] = _balances[to].ADD666(value); emit TRANSFER418(from, to, value); } function _MINT600(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD666(value); _balances[account] = _balances[account].ADD666(value); emit TRANSFER418(address(0), account, value); } function _BURN785(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB55(value); _balances[account] = _balances[account].SUB55(value); emit TRANSFER418(account, address(0), value); } function _BURNFROM615(address account, uint256 value) internal { //inject NONSTANDARD NAMING _allowed[account][msg.sender] = _allowed[account][msg.sender].SUB55(value); _BURN785(account, value); emit APPROVAL780(account, msg.sender, _allowed[account][msg.sender]); } } contract ERC20Burnable is ERC20Pistachio { bool private _burnableActive; function BURN665(uint256 value) public WHENBURNABLEACTIVE644 { //inject NONSTANDARD NAMING _BURN785(msg.sender, value); } function BURNFROM948(address from, uint256 value) public WHENBURNABLEACTIVE644 { //inject NONSTANDARD NAMING _BURNFROM615(from, value); } function _SETBURNABLEACTIVE519(bool _active) internal { //inject NONSTANDARD NAMING _burnableActive = _active; } modifier WHENBURNABLEACTIVE644() { //inject NONSTANDARD NAMING require(_burnableActive); _; } } library Roles { struct Role { mapping (address => bool) bearer; } function ADD666(Role storage role, address account) internal { //inject NONSTANDARD NAMING require(account != address(0)); require(!HAS322(role, account)); role.bearer[account] = true; } function REMOVE231(Role storage role, address account) internal { //inject NONSTANDARD NAMING require(account != address(0)); require(HAS322(role, account)); role.bearer[account] = false; } function HAS322(Role storage role, address account) internal view returns (bool) { //inject NONSTANDARD NAMING require(account != address(0)); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MINTERADDED605(address indexed account); //inject NONSTANDARD NAMING event MINTERREMOVED905(address indexed account); //inject NONSTANDARD NAMING Roles.Role private _minters; constructor () internal { _ADDMINTER929(msg.sender); } modifier ONLYMINTER785() { //inject NONSTANDARD NAMING require(ISMINTER455(msg.sender)); _; } function ISMINTER455(address account) public view returns (bool) { //inject NONSTANDARD NAMING return _minters.HAS322(account); } function ADDMINTER562(address account) public ONLYMINTER785 { //inject NONSTANDARD NAMING _ADDMINTER929(account); } function RENOUNCEMINTER297() public { //inject NONSTANDARD NAMING _REMOVEMINTER917(msg.sender); } function _ADDMINTER929(address account) internal { //inject NONSTANDARD NAMING _minters.ADD666(account); emit MINTERADDED605(account); } function _REMOVEMINTER917(address account) internal { //inject NONSTANDARD NAMING _minters.REMOVE231(account); emit MINTERREMOVED905(account); } } contract ERC20Mintable is ERC20Pistachio, MinterRole { bool private _mintableActive; function MINT525(address to, uint256 value) public ONLYMINTER785 WHENMINTABLEACTIVE702 returns (bool) { //inject NONSTANDARD NAMING _MINT600(to, value); return true; } function _SETMINTABLEACTIVE686(bool _active) internal { //inject NONSTANDARD NAMING _mintableActive = _active; } modifier WHENMINTABLEACTIVE702() { //inject NONSTANDARD NAMING require(_mintableActive); _; } } contract PauserRole { using Roles for Roles.Role; event PAUSERADDED252(address indexed account); //inject NONSTANDARD NAMING event PAUSERREMOVED538(address indexed account); //inject NONSTANDARD NAMING Roles.Role private _pausers; constructor () internal { _ADDPAUSER941(msg.sender); } modifier ONLYPAUSER672() { //inject NONSTANDARD NAMING require(ISPAUSER604(msg.sender)); _; } function ISPAUSER604(address account) public view returns (bool) { //inject NONSTANDARD NAMING return _pausers.HAS322(account); } function ADDPAUSER65(address account) public ONLYPAUSER672 { //inject NONSTANDARD NAMING _ADDPAUSER941(account); } function RENOUNCEPAUSER647() public { //inject NONSTANDARD NAMING _REMOVEPAUSER706(msg.sender); } function _ADDPAUSER941(address account) internal { //inject NONSTANDARD NAMING _pausers.ADD666(account); emit PAUSERADDED252(account); } function _REMOVEPAUSER706(address account) internal { //inject NONSTANDARD NAMING _pausers.REMOVE231(account); emit PAUSERREMOVED538(account); } } contract Pausable is PauserRole { event PAUSED114(address account); //inject NONSTANDARD NAMING event UNPAUSED110(address account); //inject NONSTANDARD NAMING bool private _pausableActive; bool private _paused; constructor () internal { _paused = false; } function PAUSED723() public view returns (bool) { //inject NONSTANDARD NAMING return _paused; } modifier WHENNOTPAUSED424() { //inject NONSTANDARD NAMING require(!_paused); _; } modifier WHENPAUSED745() { //inject NONSTANDARD NAMING require(_paused); _; } function PAUSE827() public ONLYPAUSER672 WHENNOTPAUSED424 WHENPAUSABLEACTIVE658 { //inject NONSTANDARD NAMING _paused = true; emit PAUSED114(msg.sender); } function UNPAUSE942() public ONLYPAUSER672 WHENPAUSED745 WHENPAUSABLEACTIVE658 { //inject NONSTANDARD NAMING _paused = false; emit UNPAUSED110(msg.sender); } function _SETPAUSABLEACTIVE337(bool _active) internal { //inject NONSTANDARD NAMING _pausableActive = _active; } modifier WHENPAUSABLEACTIVE658() { //inject NONSTANDARD NAMING require(_pausableActive); _; } } contract ERC20Chocolate is ERC20Pistachio, ERC20Burnable, ERC20Mintable, Pausable { // maximum capital, if defined > 0 uint256 private _cap; constructor ( address initialAccount, string memory _tokenSymbol, string memory _tokenName, uint256 initialBalance, uint256 cap, bool _burnableOption, bool _mintableOption, bool _pausableOption ) public ERC20Pistachio(initialAccount, _tokenSymbol, _tokenName, initialBalance) { // we must add customer account as the first minter ADDMINTER562(initialAccount); // add customer as pauser ADDPAUSER65(initialAccount); if (cap > 0) { _cap = cap; // maximum capitalization limited } else { _cap = 0; // unlimited capitalization } // activate or deactivate options _SETBURNABLEACTIVE519(_burnableOption); _SETMINTABLEACTIVE686(_mintableOption); _SETPAUSABLEACTIVE337(_pausableOption); } function CAP794() public view returns (uint256) { //inject NONSTANDARD NAMING return _cap; } function _MINT600(address account, uint256 value) internal { //inject NONSTANDARD NAMING if (_cap > 0) { require(TOTALSUPPLY304().ADD666(value) <= _cap); } super._MINT600(account, value); } function TRANSFER854(address to, uint256 value) public WHENNOTPAUSED424 returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFER854(to, value); } function TRANSFERFROM522(address from,address to, uint256 value) public WHENNOTPAUSED424 returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFERFROM522(from, to, value); } function APPROVE531(address spender, uint256 value) public WHENNOTPAUSED424 returns (bool) { //inject NONSTANDARD NAMING return super.APPROVE531(spender, value); } function INCREASEALLOWANCE330(address spender, uint addedValue) public WHENNOTPAUSED424 returns (bool success) { //inject NONSTANDARD NAMING return super.INCREASEALLOWANCE330(spender, addedValue); } function DECREASEALLOWANCE446(address spender, uint subtractedValue) public WHENNOTPAUSED424 returns (bool success) { //inject NONSTANDARD NAMING return super.DECREASEALLOWANCE446(spender, subtractedValue); } } contract ReentrancyGuard { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } modifier NONREENTRANT377() { //inject NONSTANDARD NAMING _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER714(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.TRANSFER854.selector, to, value)); } function SAFETRANSFERFROM672(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.TRANSFERFROM522.selector, from, to, value)); } function SAFEAPPROVE372(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE123(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.APPROVE531.selector, spender, value)); } function SAFEINCREASEALLOWANCE265(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE123(address(this), spender).ADD666(value); CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.APPROVE531.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE998(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE123(address(this), spender).SUB55(value); CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.APPROVE531.selector, spender, newAllowance)); } function CALLOPTIONALRETURN667(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // 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).ISCONTRACT761(), "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"); } } } library Address { function ISCONTRACT761(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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. // 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 != 0x0 && codehash != accountHash); } function TOPAYABLE851(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } } contract Crowdsale is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for ERC20Chocolate; // The token being sold ERC20Chocolate private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; event TOKENSPURCHASED287(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //inject NONSTANDARD NAMING constructor (uint256 rate, address payable wallet, ERC20Chocolate token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; } function () external payable { BUYTOKENS434(msg.sender); } function TOKEN293() public view returns (IERC20) { //inject NONSTANDARD NAMING return _token; } function WALLET108() public view returns (address payable) { //inject NONSTANDARD NAMING return _wallet; } function RATE426() public view returns (uint256) { //inject NONSTANDARD NAMING return _rate; } function WEIRAISED13() public view returns (uint256) { //inject NONSTANDARD NAMING return _weiRaised; } function BUYTOKENS434(address beneficiary) public NONREENTRANT377 payable { //inject NONSTANDARD NAMING uint256 weiAmount = msg.value; _PREVALIDATEPURCHASE289(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _GETTOKENAMOUNT276(weiAmount); // update state _weiRaised = _weiRaised.ADD666(weiAmount); _PROCESSPURCHASE887(beneficiary, tokens); emit TOKENSPURCHASED287(msg.sender, beneficiary, weiAmount, tokens); _UPDATEPURCHASINGSTATE322(beneficiary, weiAmount); _FORWARDFUNDS963(); _POSTVALIDATEPURCHASE368(beneficiary, weiAmount); } function _PREVALIDATEPURCHASE289(address beneficiary, uint256 weiAmount) internal view { //inject NONSTANDARD NAMING require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); } function _POSTVALIDATEPURCHASE368(address beneficiary, uint256 weiAmount) internal view { //inject NONSTANDARD NAMING // solhint-disable-previous-line no-empty-blocks } function _DELIVERTOKENS47(address beneficiary, uint256 tokenAmount) internal { //inject NONSTANDARD NAMING _token.SAFETRANSFER714(beneficiary, tokenAmount); } function _PROCESSPURCHASE887(address beneficiary, uint256 tokenAmount) internal { //inject NONSTANDARD NAMING _DELIVERTOKENS47(beneficiary, tokenAmount); } function _UPDATEPURCHASINGSTATE322(address beneficiary, uint256 weiAmount) internal { //inject NONSTANDARD NAMING // solhint-disable-previous-line no-empty-blocks } function _GETTOKENAMOUNT276(uint256 weiAmount) internal view returns (uint256) { //inject NONSTANDARD NAMING return weiAmount.MUL578(_rate); } function _FORWARDFUNDS963() internal { //inject NONSTANDARD NAMING _wallet.transfer(msg.value); } } contract MintedCrowdsale is Crowdsale { function _DELIVERTOKENS47(address beneficiary, uint256 tokenAmount) internal { //inject NONSTANDARD NAMING // Potentially dangerous assumption about the type of the token. require( ERC20Mintable(address(TOKEN293())).MINT525(beneficiary, tokenAmount), "MintedCrowdsale: minting failed" ); } } contract PausableCrowdsale is Crowdsale, Pausable { function _PREVALIDATEPURCHASE289(address _beneficiary, uint256 _weiAmount) internal view WHENNOTPAUSED424 { //inject NONSTANDARD NAMING return super._PREVALIDATEPURCHASE289(_beneficiary, _weiAmount); } } contract CrowdsaleRaspberry is MintedCrowdsale, PausableCrowdsale { constructor (uint256 rate, address payable wallet, ERC20Chocolate token, bool _isPausable) public Crowdsale(rate, wallet, token) { // solhint-disable-previous-line no-empty-blocks _SETPAUSABLEACTIVE337(_isPausable); } }
inject NONSTANDARD NAMING
function CALLOPTIONALRETURN667(IERC20 token, bytes memory data) private {
12,598,105
./partial_match/1/0x35DDEFa2a30474E64314aAA7370abE14c042C6e8/sources/RariFundProxy.sol
Ensures that only transactions with a trusted signature can be relayed through the GSN./
function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 ) external view returns (uint256, bytes memory) { bytes memory blob = abi.encodePacked( relay, from, encodedFunction, transactionFee, gasPrice, gasLimit, ); if (keccak256(blob).toEthSignedMessageHash().recover(approvalData) != _gsnTrustedSigner) return _rejectRelayedCall(0); if (_gsnTrustedSigner == address(0)) return _rejectRelayedCall(1); return _approveRelayedCall(); }
3,558,610
./partial_match/1/0x561d0d6c498a379574eAaA4a5F2532b223fFaeBF/sources/NESTSave.sol
Change mapping contract map Mapping contract address/
function changeMapping(address map) public onlyOwner { mappingContract = IBMapping(map); }
9,205,205
./full_match/1/0x874e1B98eb3150530Dc410Bb1512f032AEcf0a27/sources/browser/new_yBXTBService2.sol
For USDT Interface Changed 'constant' to 'view' for compiler 0.5.4
interface ERC20_USDT { function totalSupply() external view returns (uint); function balanceOf(address who) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function transfer(address to, uint value) external; function approve(address spender, uint value) external; function transferFrom(address from, address to, uint value) external; }
8,490,669
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@bancor/token-governance/contracts/ITokenGovernance.sol"; import "../utility/interfaces/ICheckpointStore.sol"; import "../utility/MathEx.sol"; import "../utility/Types.sol"; import "../utility/Time.sol"; import "../utility/Utils.sol"; import "../utility/Owned.sol"; import "../token/interfaces/IDSToken.sol"; import "../token/ReserveToken.sol"; import "../converter/interfaces/IConverterAnchor.sol"; import "../converter/interfaces/IConverter.sol"; import "../converter/interfaces/IConverterRegistry.sol"; import "./interfaces/ILiquidityProtection.sol"; interface ILiquidityPoolConverter is IConverter { function addLiquidity( IReserveToken[] memory reserveTokens, uint256[] memory reserveAmounts, uint256 _minReturn ) external payable; function removeLiquidity( uint256 amount, IReserveToken[] memory reserveTokens, uint256[] memory _reserveMinReturnAmounts ) external; function recentAverageRate(IReserveToken reserveToken) external view returns (uint256, uint256); } /** * @dev This contract implements the liquidity protection mechanism. */ contract LiquidityProtection is ILiquidityProtection, Utils, Owned, ReentrancyGuard, Time { using SafeMath for uint256; using ReserveToken for IReserveToken; using SafeERC20 for IERC20; using SafeERC20 for IDSToken; using SafeERC20Ex for IERC20; using MathEx for *; struct Position { address provider; // liquidity provider IDSToken poolToken; // pool token address IReserveToken reserveToken; // reserve token address uint256 poolAmount; // pool token amount uint256 reserveAmount; // reserve token amount uint256 reserveRateN; // rate of 1 protected reserve token in units of the other reserve token (numerator) uint256 reserveRateD; // rate of 1 protected reserve token in units of the other reserve token (denominator) uint256 timestamp; // timestamp } // various rates between the two reserve tokens. the rate is of 1 unit of the protected reserve token in units of the other reserve token struct PackedRates { uint128 addSpotRateN; // spot rate of 1 A in units of B when liquidity was added (numerator) uint128 addSpotRateD; // spot rate of 1 A in units of B when liquidity was added (denominator) uint128 removeSpotRateN; // spot rate of 1 A in units of B when liquidity is removed (numerator) uint128 removeSpotRateD; // spot rate of 1 A in units of B when liquidity is removed (denominator) uint128 removeAverageRateN; // average rate of 1 A in units of B when liquidity is removed (numerator) uint128 removeAverageRateD; // average rate of 1 A in units of B when liquidity is removed (denominator) } uint256 internal constant MAX_UINT128 = 2**128 - 1; uint256 internal constant MAX_UINT256 = uint256(-1); ILiquidityProtectionSettings private immutable _settings; ILiquidityProtectionStore private immutable _store; ILiquidityProtectionStats private immutable _stats; ILiquidityProtectionSystemStore private immutable _systemStore; ITokenHolder private immutable _wallet; IERC20 private immutable _networkToken; ITokenGovernance private immutable _networkTokenGovernance; IERC20 private immutable _govToken; ITokenGovernance private immutable _govTokenGovernance; ICheckpointStore private immutable _lastRemoveCheckpointStore; /** * @dev initializes a new LiquidityProtection contract * * @param settings liquidity protection settings * @param store liquidity protection store * @param stats liquidity protection stats * @param systemStore liquidity protection system store * @param wallet liquidity protection wallet * @param networkTokenGovernance network token governance * @param govTokenGovernance governance token governance * @param lastRemoveCheckpointStore last liquidity removal/unprotection checkpoints store */ constructor( ILiquidityProtectionSettings settings, ILiquidityProtectionStore store, ILiquidityProtectionStats stats, ILiquidityProtectionSystemStore systemStore, ITokenHolder wallet, ITokenGovernance networkTokenGovernance, ITokenGovernance govTokenGovernance, ICheckpointStore lastRemoveCheckpointStore ) public validAddress(address(settings)) validAddress(address(store)) validAddress(address(stats)) validAddress(address(systemStore)) validAddress(address(wallet)) validAddress(address(lastRemoveCheckpointStore)) { _settings = settings; _store = store; _stats = stats; _systemStore = systemStore; _wallet = wallet; _networkTokenGovernance = networkTokenGovernance; _govTokenGovernance = govTokenGovernance; _lastRemoveCheckpointStore = lastRemoveCheckpointStore; _networkToken = networkTokenGovernance.token(); _govToken = govTokenGovernance.token(); } // ensures that the pool is supported and whitelisted modifier poolSupportedAndWhitelisted(IConverterAnchor poolAnchor) { _poolSupported(poolAnchor); _poolWhitelisted(poolAnchor); _; } // ensures that add liquidity is enabled modifier addLiquidityEnabled(IConverterAnchor poolAnchor, IReserveToken reserveToken) { _addLiquidityEnabled(poolAnchor, reserveToken); _; } // error message binary size optimization function _poolSupported(IConverterAnchor poolAnchor) internal view { require(_settings.isPoolSupported(poolAnchor), "ERR_POOL_NOT_SUPPORTED"); } // error message binary size optimization function _poolWhitelisted(IConverterAnchor poolAnchor) internal view { require(_settings.isPoolWhitelisted(poolAnchor), "ERR_POOL_NOT_WHITELISTED"); } // error message binary size optimization function _addLiquidityEnabled(IConverterAnchor poolAnchor, IReserveToken reserveToken) internal view { require(!_settings.addLiquidityDisabled(poolAnchor, reserveToken), "ERR_ADD_LIQUIDITY_DISABLED"); } // error message binary size optimization function verifyEthAmount(uint256 value) internal view { require(msg.value == value, "ERR_ETH_AMOUNT_MISMATCH"); } /** * @dev returns the LP store * * @return the LP store */ function store() external view override returns (ILiquidityProtectionStore) { return _store; } /** * @dev returns the LP stats * * @return the LP stats */ function stats() external view override returns (ILiquidityProtectionStats) { return _stats; } /** * @dev returns the LP settings * * @return the LP settings */ function settings() external view override returns (ILiquidityProtectionSettings) { return _settings; } /** * @dev returns the LP system store * * @return the LP system store */ function systemStore() external view override returns (ILiquidityProtectionSystemStore) { return _systemStore; } /** * @dev returns the LP wallet * * @return the LP wallet */ function wallet() external view override returns (ITokenHolder) { return _wallet; } /** * @dev accept ETH */ receive() external payable {} /** * @dev transfers the ownership of the store * can only be called by the contract owner * * @param newOwner the new owner of the store */ function transferStoreOwnership(address newOwner) external ownerOnly { _store.transferOwnership(newOwner); } /** * @dev accepts the ownership of the store * can only be called by the contract owner */ function acceptStoreOwnership() external ownerOnly { _store.acceptOwnership(); } /** * @dev transfers the ownership of the wallet * can only be called by the contract owner * * @param newOwner the new owner of the wallet */ function transferWalletOwnership(address newOwner) external ownerOnly { _wallet.transferOwnership(newOwner); } /** * @dev accepts the ownership of the wallet * can only be called by the contract owner */ function acceptWalletOwnership() external ownerOnly { _wallet.acceptOwnership(); } /** * @dev adds protected liquidity to a pool for a specific recipient * also mints new governance tokens for the caller if the caller adds network tokens * * @param owner position owner * @param poolAnchor anchor of the pool * @param reserveToken reserve token to add to the pool * @param amount amount of tokens to add to the pool * * @return new position id */ function addLiquidityFor( address owner, IConverterAnchor poolAnchor, IReserveToken reserveToken, uint256 amount ) external payable override nonReentrant validAddress(owner) poolSupportedAndWhitelisted(poolAnchor) addLiquidityEnabled(poolAnchor, reserveToken) greaterThanZero(amount) returns (uint256) { return addLiquidity(owner, poolAnchor, reserveToken, amount); } /** * @dev adds protected liquidity to a pool * also mints new governance tokens for the caller if the caller adds network tokens * * @param poolAnchor anchor of the pool * @param reserveToken reserve token to add to the pool * @param amount amount of tokens to add to the pool * * @return new position id */ function addLiquidity( IConverterAnchor poolAnchor, IReserveToken reserveToken, uint256 amount ) external payable override nonReentrant poolSupportedAndWhitelisted(poolAnchor) addLiquidityEnabled(poolAnchor, reserveToken) greaterThanZero(amount) returns (uint256) { return addLiquidity(msg.sender, poolAnchor, reserveToken, amount); } /** * @dev adds protected liquidity to a pool for a specific recipient * also mints new governance tokens for the caller if the caller adds network tokens * * @param owner position owner * @param poolAnchor anchor of the pool * @param reserveToken reserve token to add to the pool * @param amount amount of tokens to add to the pool * * @return new position id */ function addLiquidity( address owner, IConverterAnchor poolAnchor, IReserveToken reserveToken, uint256 amount ) private returns (uint256) { if (isNetworkToken(reserveToken)) { verifyEthAmount(0); return addNetworkTokenLiquidity(owner, poolAnchor, amount); } // verify that ETH was passed with the call if needed verifyEthAmount(reserveToken.isNativeToken() ? amount : 0); return addBaseTokenLiquidity(owner, poolAnchor, reserveToken, amount); } /** * @dev adds network token liquidity to a pool * also mints new governance tokens for the caller * * @param owner position owner * @param poolAnchor anchor of the pool * @param amount amount of tokens to add to the pool * * @return new position id */ function addNetworkTokenLiquidity( address owner, IConverterAnchor poolAnchor, uint256 amount ) internal returns (uint256) { IDSToken poolToken = IDSToken(address(poolAnchor)); IReserveToken networkToken = IReserveToken(address(_networkToken)); // get the rate between the pool token and the reserve Fraction memory poolRate = poolTokenRate(poolToken, networkToken); // calculate the amount of pool tokens based on the amount of reserve tokens uint256 poolTokenAmount = amount.mul(poolRate.d).div(poolRate.n); // remove the pool tokens from the system's ownership (will revert if not enough tokens are available) _systemStore.decSystemBalance(poolToken, poolTokenAmount); // add the position for the recipient uint256 id = addPosition(owner, poolToken, networkToken, poolTokenAmount, amount, time()); // burns the network tokens from the caller. we need to transfer the tokens to the contract itself, since only // token holders can burn their tokens _networkToken.safeTransferFrom(msg.sender, address(this), amount); burnNetworkTokens(poolAnchor, amount); // mint governance tokens to the recipient _govTokenGovernance.mint(owner, amount); return id; } /** * @dev adds base token liquidity to a pool * * @param owner position owner * @param poolAnchor anchor of the pool * @param baseToken the base reserve token of the pool * @param amount amount of tokens to add to the pool * * @return new position id */ function addBaseTokenLiquidity( address owner, IConverterAnchor poolAnchor, IReserveToken baseToken, uint256 amount ) internal returns (uint256) { IDSToken poolToken = IDSToken(address(poolAnchor)); IReserveToken networkToken = IReserveToken(address(_networkToken)); // get the reserve balances ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(poolAnchor))); (uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) = converterReserveBalances(converter, baseToken, networkToken); require(reserveBalanceNetwork >= _settings.minNetworkTokenLiquidityForMinting(), "ERR_NOT_ENOUGH_LIQUIDITY"); // calculate and mint the required amount of network tokens for adding liquidity uint256 newNetworkLiquidityAmount = amount.mul(reserveBalanceNetwork).div(reserveBalanceBase); // verify network token minting limit uint256 mintingLimit = _settings.networkTokenMintingLimits(poolAnchor); if (mintingLimit == 0) { mintingLimit = _settings.defaultNetworkTokenMintingLimit(); } uint256 newNetworkTokensMinted = _systemStore.networkTokensMinted(poolAnchor).add(newNetworkLiquidityAmount); require(newNetworkTokensMinted <= mintingLimit, "ERR_MAX_AMOUNT_REACHED"); // issue new network tokens to the system mintNetworkTokens(address(this), poolAnchor, newNetworkLiquidityAmount); // transfer the base tokens from the caller and approve the converter networkToken.ensureApprove(address(converter), newNetworkLiquidityAmount); if (!baseToken.isNativeToken()) { baseToken.safeTransferFrom(msg.sender, address(this), amount); baseToken.ensureApprove(address(converter), amount); } // add the liquidity to the converter addLiquidity(converter, baseToken, networkToken, amount, newNetworkLiquidityAmount, msg.value); // transfer the new pool tokens to the wallet uint256 poolTokenAmount = poolToken.balanceOf(address(this)); poolToken.safeTransfer(address(_wallet), poolTokenAmount); // the system splits the pool tokens with the caller // increase the system's pool token balance and add the position for the caller _systemStore.incSystemBalance(poolToken, poolTokenAmount - poolTokenAmount / 2); // account for rounding errors return addPosition(owner, poolToken, baseToken, poolTokenAmount / 2, amount, time()); } /** * @dev returns the single-side staking limits of a given pool * * @param poolAnchor anchor of the pool * * @return maximum amount of base tokens that can be single-side staked in the pool * @return maximum amount of network tokens that can be single-side staked in the pool */ function poolAvailableSpace(IConverterAnchor poolAnchor) external view poolSupportedAndWhitelisted(poolAnchor) returns (uint256, uint256) { return (baseTokenAvailableSpace(poolAnchor), networkTokenAvailableSpace(poolAnchor)); } /** * @dev returns the base-token staking limits of a given pool * * @param poolAnchor anchor of the pool * * @return maximum amount of base tokens that can be single-side staked in the pool */ function baseTokenAvailableSpace(IConverterAnchor poolAnchor) internal view returns (uint256) { // get the pool converter ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(poolAnchor))); // get the base token IReserveToken networkToken = IReserveToken(address(_networkToken)); IReserveToken baseToken = converterOtherReserve(converter, networkToken); // get the reserve balances (uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) = converterReserveBalances(converter, baseToken, networkToken); // get the network token minting limit uint256 mintingLimit = _settings.networkTokenMintingLimits(poolAnchor); if (mintingLimit == 0) { mintingLimit = _settings.defaultNetworkTokenMintingLimit(); } // get the amount of network tokens already minted for the pool uint256 networkTokensMinted = _systemStore.networkTokensMinted(poolAnchor); // get the amount of network tokens which can minted for the pool uint256 networkTokensCanBeMinted = MathEx.max(mintingLimit, networkTokensMinted) - networkTokensMinted; // return the maximum amount of base token liquidity that can be single-sided staked in the pool return networkTokensCanBeMinted.mul(reserveBalanceBase).div(reserveBalanceNetwork); } /** * @dev returns the network-token staking limits of a given pool * * @param poolAnchor anchor of the pool * * @return maximum amount of network tokens that can be single-side staked in the pool */ function networkTokenAvailableSpace(IConverterAnchor poolAnchor) internal view returns (uint256) { // get the pool token IDSToken poolToken = IDSToken(address(poolAnchor)); IReserveToken networkToken = IReserveToken(address(_networkToken)); // get the pool token rate Fraction memory poolRate = poolTokenRate(poolToken, networkToken); // return the maximum amount of network token liquidity that can be single-sided staked in the pool return _systemStore.systemBalance(poolToken).mul(poolRate.n).add(poolRate.n).sub(1).div(poolRate.d); } /** * @dev returns the expected/actual amounts the provider will receive for removing liquidity * it's also possible to provide the remove liquidity time to get an estimation * for the return at that given point * * @param id position id * @param portion portion of liquidity to remove, in PPM * @param removeTimestamp time at which the liquidity is removed * * @return expected return amount in the reserve token * @return actual return amount in the reserve token * @return compensation in the network token */ function removeLiquidityReturn( uint256 id, uint32 portion, uint256 removeTimestamp ) external view validPortion(portion) returns ( uint256, uint256, uint256 ) { Position memory pos = position(id); // verify input require(pos.provider != address(0), "ERR_INVALID_ID"); require(removeTimestamp >= pos.timestamp, "ERR_INVALID_TIMESTAMP"); // calculate the portion of the liquidity to remove if (portion != PPM_RESOLUTION) { pos.poolAmount = pos.poolAmount.mul(portion) / PPM_RESOLUTION; pos.reserveAmount = pos.reserveAmount.mul(portion) / PPM_RESOLUTION; } // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates(pos.poolToken, pos.reserveToken, pos.reserveRateN, pos.reserveRateD); uint256 targetAmount = removeLiquidityTargetAmount( pos.poolToken, pos.reserveToken, pos.poolAmount, pos.reserveAmount, packedRates, pos.timestamp, removeTimestamp ); // for network token, the return amount is identical to the target amount if (isNetworkToken(pos.reserveToken)) { return (targetAmount, targetAmount, 0); } // handle base token return // calculate the amount of pool tokens required for liquidation // note that the amount is doubled since it's not possible to liquidate one reserve only Fraction memory poolRate = poolTokenRate(pos.poolToken, pos.reserveToken); uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2); // limit the amount of pool tokens by the amount the system/caller holds uint256 availableBalance = _systemStore.systemBalance(pos.poolToken).add(pos.poolAmount); poolAmount = poolAmount > availableBalance ? availableBalance : poolAmount; // calculate the base token amount received by liquidating the pool tokens // note that the amount is divided by 2 since the pool amount represents both reserves uint256 baseAmount = poolAmount.mul(poolRate.n / 2).div(poolRate.d); uint256 networkAmount = networkCompensation(targetAmount, baseAmount, packedRates); return (targetAmount, baseAmount, networkAmount); } /** * @dev removes protected liquidity from a pool * also burns governance tokens from the caller if the caller removes network tokens * * @param id position id * @param portion portion of liquidity to remove, in PPM */ function removeLiquidity(uint256 id, uint32 portion) external override nonReentrant validPortion(portion) { removeLiquidity(msg.sender, id, portion); } /** * @dev removes a position from a pool * also burns governance tokens from the caller if the caller removes network tokens * * @param provider liquidity provider * @param id position id * @param portion portion of liquidity to remove, in PPM */ function removeLiquidity( address payable provider, uint256 id, uint32 portion ) internal { // remove the position from the store and update the stats and the last removal checkpoint Position memory removedPos = removePosition(provider, id, portion); // add the pool tokens to the system _systemStore.incSystemBalance(removedPos.poolToken, removedPos.poolAmount); // if removing network token liquidity, burn the governance tokens from the caller. we need to transfer the // tokens to the contract itself, since only token holders can burn their tokens if (isNetworkToken(removedPos.reserveToken)) { _govToken.safeTransferFrom(provider, address(this), removedPos.reserveAmount); _govTokenGovernance.burn(removedPos.reserveAmount); } // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates(removedPos.poolToken, removedPos.reserveToken, removedPos.reserveRateN, removedPos.reserveRateD); // verify rate deviation as early as possible in order to reduce gas-cost for failing transactions verifyRateDeviation( packedRates.removeSpotRateN, packedRates.removeSpotRateD, packedRates.removeAverageRateN, packedRates.removeAverageRateD ); // get the target token amount uint256 targetAmount = removeLiquidityTargetAmount( removedPos.poolToken, removedPos.reserveToken, removedPos.poolAmount, removedPos.reserveAmount, packedRates, removedPos.timestamp, time() ); // remove network token liquidity if (isNetworkToken(removedPos.reserveToken)) { // mint network tokens for the caller and lock them mintNetworkTokens(address(_wallet), removedPos.poolToken, targetAmount); lockTokens(provider, targetAmount); return; } // remove base token liquidity // calculate the amount of pool tokens required for liquidation // note that the amount is doubled since it's not possible to liquidate one reserve only Fraction memory poolRate = poolTokenRate(removedPos.poolToken, removedPos.reserveToken); uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2); // limit the amount of pool tokens by the amount the system holds uint256 systemBalance = _systemStore.systemBalance(removedPos.poolToken); poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount; // withdraw the pool tokens from the wallet IReserveToken poolToken = IReserveToken(address(removedPos.poolToken)); _systemStore.decSystemBalance(removedPos.poolToken, poolAmount); _wallet.withdrawTokens(poolToken, address(this), poolAmount); // remove liquidity removeLiquidity( removedPos.poolToken, poolAmount, removedPos.reserveToken, IReserveToken(address(_networkToken)) ); // transfer the base tokens to the caller uint256 baseBalance = removedPos.reserveToken.balanceOf(address(this)); removedPos.reserveToken.safeTransfer(provider, baseBalance); // compensate the caller with network tokens if still needed uint256 delta = networkCompensation(targetAmount, baseBalance, packedRates); if (delta > 0) { // check if there's enough network token balance, otherwise mint more uint256 networkBalance = _networkToken.balanceOf(address(this)); if (networkBalance < delta) { _networkTokenGovernance.mint(address(this), delta - networkBalance); } // lock network tokens for the caller _networkToken.safeTransfer(address(_wallet), delta); lockTokens(provider, delta); } // if the contract still holds network tokens, burn them uint256 networkBalance = _networkToken.balanceOf(address(this)); if (networkBalance > 0) { burnNetworkTokens(removedPos.poolToken, networkBalance); } } /** * @dev returns the amount the provider will receive for removing liquidity * it's also possible to provide the remove liquidity rate & time to get an estimation * for the return at that given point * * @param poolToken pool token * @param reserveToken reserve token * @param poolAmount pool token amount when the liquidity was added * @param reserveAmount reserve token amount that was added * @param packedRates see `struct PackedRates` * @param addTimestamp time at which the liquidity was added * @param removeTimestamp time at which the liquidity is removed * * @return amount received for removing liquidity */ function removeLiquidityTargetAmount( IDSToken poolToken, IReserveToken reserveToken, uint256 poolAmount, uint256 reserveAmount, PackedRates memory packedRates, uint256 addTimestamp, uint256 removeTimestamp ) internal view returns (uint256) { // get the rate between the pool token and the reserve token Fraction memory poolRate = poolTokenRate(poolToken, reserveToken); // get the rate between the reserves upon adding liquidity and now Fraction memory addSpotRate = Fraction({ n: packedRates.addSpotRateN, d: packedRates.addSpotRateD }); Fraction memory removeSpotRate = Fraction({ n: packedRates.removeSpotRateN, d: packedRates.removeSpotRateD }); Fraction memory removeAverageRate = Fraction({ n: packedRates.removeAverageRateN, d: packedRates.removeAverageRateD }); // calculate the protected amount of reserve tokens plus accumulated fee before compensation uint256 total = protectedAmountPlusFee(poolAmount, poolRate, addSpotRate, removeSpotRate); // calculate the impermanent loss Fraction memory loss = impLoss(addSpotRate, removeAverageRate); // calculate the protection level Fraction memory level = protectionLevel(addTimestamp, removeTimestamp); // calculate the compensation amount return compensationAmount(reserveAmount, MathEx.max(reserveAmount, total), loss, level); } /** * @dev transfers a position to a new provider * * @param id position id * @param newProvider the new provider * * @return new position id */ function transferPosition(uint256 id, address newProvider) external override nonReentrant validAddress(newProvider) returns (uint256) { return transferPosition(msg.sender, id, newProvider); } /** * @dev transfers a position to a new provider and optionally notifies another contract * * @param id position id * @param newProvider the new provider * @param callback the callback contract to notify * @param data custom data provided to the callback * * @return new position id */ function transferPositionAndNotify( uint256 id, address newProvider, ITransferPositionCallback callback, bytes calldata data ) external override nonReentrant validAddress(newProvider) validAddress(address(callback)) returns (uint256) { uint256 newId = transferPosition(msg.sender, id, newProvider); callback.onTransferPosition(newId, msg.sender, data); return newId; } /** * @dev transfers a position to a new provider * * @param provider the existing provider * @param id position id * @param newProvider the new provider * * @return new position id */ function transferPosition( address provider, uint256 id, address newProvider ) internal returns (uint256) { // remove the position from the store and update the stats and the last removal checkpoint Position memory removedPos = removePosition(provider, id, PPM_RESOLUTION); // add the position to the store, update the stats, and return the new id return addPosition( newProvider, removedPos.poolToken, removedPos.reserveToken, removedPos.poolAmount, removedPos.reserveAmount, removedPos.timestamp ); } /** * @dev allows the caller to claim network token balance that is no longer locked * note that the function can revert if the range is too large * * @param startIndex start index in the caller's list of locked balances * @param endIndex end index in the caller's list of locked balances (exclusive) */ function claimBalance(uint256 startIndex, uint256 endIndex) external nonReentrant { // get the locked balances from the store (uint256[] memory amounts, uint256[] memory expirationTimes) = _store.lockedBalanceRange(msg.sender, startIndex, endIndex); uint256 totalAmount = 0; uint256 length = amounts.length; assert(length == expirationTimes.length); // reverse iteration since we're removing from the list for (uint256 i = length; i > 0; i--) { uint256 index = i - 1; if (expirationTimes[index] > time()) { continue; } // remove the locked balance item _store.removeLockedBalance(msg.sender, startIndex + index); totalAmount = totalAmount.add(amounts[index]); } if (totalAmount > 0) { // transfer the tokens to the caller in a single call _wallet.withdrawTokens(IReserveToken(address(_networkToken)), msg.sender, totalAmount); } } /** * @dev returns the ROI for removing liquidity in the current state after providing liquidity with the given args * the function assumes full protection is in effect * return value is in PPM and can be larger than PPM_RESOLUTION for positive ROI, 1M = 0% ROI * * @param poolToken pool token * @param reserveToken reserve token * @param reserveAmount reserve token amount that was added * @param poolRateN rate of 1 pool token in reserve token units when the liquidity was added (numerator) * @param poolRateD rate of 1 pool token in reserve token units when the liquidity was added (denominator) * @param reserveRateN rate of 1 reserve token in the other reserve token units when the liquidity was added (numerator) * @param reserveRateD rate of 1 reserve token in the other reserve token units when the liquidity was added (denominator) * * @return ROI in PPM */ function poolROI( IDSToken poolToken, IReserveToken reserveToken, uint256 reserveAmount, uint256 poolRateN, uint256 poolRateD, uint256 reserveRateN, uint256 reserveRateD ) external view returns (uint256) { // calculate the amount of pool tokens based on the amount of reserve tokens uint256 poolAmount = reserveAmount.mul(poolRateD).div(poolRateN); // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates(poolToken, reserveToken, reserveRateN, reserveRateD); // get the current return uint256 protectedReturn = removeLiquidityTargetAmount( poolToken, reserveToken, poolAmount, reserveAmount, packedRates, time().sub(_settings.maxProtectionDelay()), time() ); // calculate the ROI as the ratio between the current fully protected return and the initial amount return protectedReturn.mul(PPM_RESOLUTION).div(reserveAmount); } /** * @dev adds the position to the store and updates the stats * * @param provider the provider * @param poolToken pool token * @param reserveToken reserve token * @param poolAmount amount of pool tokens to protect * @param reserveAmount amount of reserve tokens to protect * @param timestamp the timestamp of the position * * @return new position id */ function addPosition( address provider, IDSToken poolToken, IReserveToken reserveToken, uint256 poolAmount, uint256 reserveAmount, uint256 timestamp ) internal returns (uint256) { // verify rate deviation as early as possible in order to reduce gas-cost for failing transactions (Fraction memory spotRate, Fraction memory averageRate) = reserveTokenRates(poolToken, reserveToken); verifyRateDeviation(spotRate.n, spotRate.d, averageRate.n, averageRate.d); notifyEventSubscribersOnAddingLiquidity(provider, poolToken, reserveToken, poolAmount, reserveAmount); _stats.increaseTotalAmounts(provider, poolToken, reserveToken, poolAmount, reserveAmount); _stats.addProviderPool(provider, poolToken); return _store.addProtectedLiquidity( provider, poolToken, reserveToken, poolAmount, reserveAmount, spotRate.n, spotRate.d, timestamp ); } /** * @dev removes the position from the store and updates the stats and the last removal checkpoint * * @param provider the provider * @param id position id * @param portion portion of the position to remove, in PPM * * @return a Position struct representing the removed liquidity */ function removePosition( address provider, uint256 id, uint32 portion ) private returns (Position memory) { Position memory pos = providerPosition(id, provider); // verify that the pool is whitelisted _poolWhitelisted(pos.poolToken); // verify that the position is not removed on the same block in which it was added require(pos.timestamp < time(), "ERR_TOO_EARLY"); if (portion == PPM_RESOLUTION) { notifyEventSubscribersOnRemovingLiquidity( id, pos.provider, pos.poolToken, pos.reserveToken, pos.poolAmount, pos.reserveAmount ); // remove the position from the provider _store.removeProtectedLiquidity(id); } else { // remove a portion of the position from the provider uint256 fullPoolAmount = pos.poolAmount; uint256 fullReserveAmount = pos.reserveAmount; pos.poolAmount = pos.poolAmount.mul(portion) / PPM_RESOLUTION; pos.reserveAmount = pos.reserveAmount.mul(portion) / PPM_RESOLUTION; notifyEventSubscribersOnRemovingLiquidity( id, pos.provider, pos.poolToken, pos.reserveToken, pos.poolAmount, pos.reserveAmount ); _store.updateProtectedLiquidityAmounts( id, fullPoolAmount - pos.poolAmount, fullReserveAmount - pos.reserveAmount ); } // update the statistics _stats.decreaseTotalAmounts(pos.provider, pos.poolToken, pos.reserveToken, pos.poolAmount, pos.reserveAmount); // update last liquidity removal checkpoint _lastRemoveCheckpointStore.addCheckpoint(provider); return pos; } /** * @dev locks network tokens for the provider and emits the tokens locked event * * @param provider tokens provider * @param amount amount of network tokens */ function lockTokens(address provider, uint256 amount) internal { uint256 expirationTime = time().add(_settings.lockDuration()); _store.addLockedBalance(provider, amount, expirationTime); } /** * @dev returns the rate of 1 pool token in reserve token units * * @param poolToken pool token * @param reserveToken reserve token */ function poolTokenRate(IDSToken poolToken, IReserveToken reserveToken) internal view virtual returns (Fraction memory) { // get the pool token supply uint256 poolTokenSupply = poolToken.totalSupply(); // get the reserve balance IConverter converter = IConverter(payable(ownedBy(poolToken))); uint256 reserveBalance = converter.getConnectorBalance(reserveToken); // for standard pools, 50% of the pool supply value equals the value of each reserve return Fraction({ n: reserveBalance.mul(2), d: poolTokenSupply }); } /** * @dev returns the spot rate and average rate of 1 reserve token in the other reserve token units * * @param poolToken pool token * @param reserveToken reserve token * * @return spot rate * @return average rate */ function reserveTokenRates(IDSToken poolToken, IReserveToken reserveToken) internal view returns (Fraction memory, Fraction memory) { ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(poolToken))); IReserveToken otherReserve = converterOtherReserve(converter, reserveToken); (uint256 spotRateN, uint256 spotRateD) = converterReserveBalances(converter, otherReserve, reserveToken); (uint256 averageRateN, uint256 averageRateD) = converter.recentAverageRate(reserveToken); return (Fraction({ n: spotRateN, d: spotRateD }), Fraction({ n: averageRateN, d: averageRateD })); } /** * @dev returns the various rates between the reserves * * @param poolToken pool token * @param reserveToken reserve token * @param addSpotRateN add spot rate numerator * @param addSpotRateD add spot rate denominator * * @return see `struct PackedRates` */ function packRates( IDSToken poolToken, IReserveToken reserveToken, uint256 addSpotRateN, uint256 addSpotRateD ) internal view returns (PackedRates memory) { (Fraction memory removeSpotRate, Fraction memory removeAverageRate) = reserveTokenRates(poolToken, reserveToken); assert( addSpotRateN <= MAX_UINT128 && addSpotRateD <= MAX_UINT128 && removeSpotRate.n <= MAX_UINT128 && removeSpotRate.d <= MAX_UINT128 && removeAverageRate.n <= MAX_UINT128 && removeAverageRate.d <= MAX_UINT128 ); return PackedRates({ addSpotRateN: uint128(addSpotRateN), addSpotRateD: uint128(addSpotRateD), removeSpotRateN: uint128(removeSpotRate.n), removeSpotRateD: uint128(removeSpotRate.d), removeAverageRateN: uint128(removeAverageRate.n), removeAverageRateD: uint128(removeAverageRate.d) }); } /** * @dev verifies that the deviation of the average rate from the spot rate is within the permitted range * for example, if the maximum permitted deviation is 5%, then verify `95/100 <= average/spot <= 100/95` * * @param spotRateN spot rate numerator * @param spotRateD spot rate denominator * @param averageRateN average rate numerator * @param averageRateD average rate denominator */ function verifyRateDeviation( uint256 spotRateN, uint256 spotRateD, uint256 averageRateN, uint256 averageRateD ) internal view { uint256 ppmDelta = PPM_RESOLUTION - _settings.averageRateMaxDeviation(); uint256 min = spotRateN.mul(averageRateD).mul(ppmDelta).mul(ppmDelta); uint256 mid = spotRateD.mul(averageRateN).mul(ppmDelta).mul(PPM_RESOLUTION); uint256 max = spotRateN.mul(averageRateD).mul(PPM_RESOLUTION).mul(PPM_RESOLUTION); require(min <= mid && mid <= max, "ERR_INVALID_RATE"); } /** * @dev utility to add liquidity to a converter * * @param converter converter * @param reserveToken1 reserve token 1 * @param reserveToken2 reserve token 2 * @param reserveAmount1 reserve amount 1 * @param reserveAmount2 reserve amount 2 * @param value ETH amount to add */ function addLiquidity( ILiquidityPoolConverter converter, IReserveToken reserveToken1, IReserveToken reserveToken2, uint256 reserveAmount1, uint256 reserveAmount2, uint256 value ) internal { IReserveToken[] memory reserveTokens = new IReserveToken[](2); uint256[] memory amounts = new uint256[](2); reserveTokens[0] = reserveToken1; reserveTokens[1] = reserveToken2; amounts[0] = reserveAmount1; amounts[1] = reserveAmount2; converter.addLiquidity{ value: value }(reserveTokens, amounts, 1); } /** * @dev utility to remove liquidity from a converter * * @param poolToken pool token of the converter * @param poolAmount amount of pool tokens to remove * @param reserveToken1 reserve token 1 * @param reserveToken2 reserve token 2 */ function removeLiquidity( IDSToken poolToken, uint256 poolAmount, IReserveToken reserveToken1, IReserveToken reserveToken2 ) internal { ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(poolToken))); IReserveToken[] memory reserveTokens = new IReserveToken[](2); uint256[] memory minReturns = new uint256[](2); reserveTokens[0] = reserveToken1; reserveTokens[1] = reserveToken2; minReturns[0] = 1; minReturns[1] = 1; converter.removeLiquidity(poolAmount, reserveTokens, minReturns); } /** * @dev returns a position from the store * * @param id position id * * @return a position */ function position(uint256 id) internal view returns (Position memory) { Position memory pos; ( pos.provider, pos.poolToken, pos.reserveToken, pos.poolAmount, pos.reserveAmount, pos.reserveRateN, pos.reserveRateD, pos.timestamp ) = _store.protectedLiquidity(id); return pos; } /** * @dev returns a position from the store * * @param id position id * @param provider authorized provider * * @return a position */ function providerPosition(uint256 id, address provider) internal view returns (Position memory) { Position memory pos = position(id); require(pos.provider == provider, "ERR_ACCESS_DENIED"); return pos; } /** * @dev returns the protected amount of reserve tokens plus accumulated fee before compensation * * @param poolAmount pool token amount when the liquidity was added * @param poolRate rate of 1 pool token in the related reserve token units * @param addRate rate of 1 reserve token in the other reserve token units when the liquidity was added * @param removeRate rate of 1 reserve token in the other reserve token units when the liquidity is removed * * @return protected amount of reserve tokens plus accumulated fee = sqrt(removeRate / addRate) * poolRate * poolAmount */ function protectedAmountPlusFee( uint256 poolAmount, Fraction memory poolRate, Fraction memory addRate, Fraction memory removeRate ) internal pure returns (uint256) { uint256 n = MathEx.ceilSqrt(addRate.d.mul(removeRate.n)).mul(poolRate.n); uint256 d = MathEx.floorSqrt(addRate.n.mul(removeRate.d)).mul(poolRate.d); uint256 x = n * poolAmount; if (x / n == poolAmount) { return x / d; } (uint256 hi, uint256 lo) = n > poolAmount ? (n, poolAmount) : (poolAmount, n); (uint256 p, uint256 q) = MathEx.reducedRatio(hi, d, MAX_UINT256 / lo); uint256 min = (hi / d).mul(lo); if (q > 0) { return MathEx.max(min, (p * lo) / q); } return min; } /** * @dev returns the impermanent loss incurred due to the change in rates between the reserve tokens * * @param prevRate previous rate between the reserves * @param newRate new rate between the reserves * * @return impermanent loss (as a ratio) */ function impLoss(Fraction memory prevRate, Fraction memory newRate) internal pure returns (Fraction memory) { uint256 ratioN = newRate.n.mul(prevRate.d); uint256 ratioD = newRate.d.mul(prevRate.n); uint256 prod = ratioN * ratioD; uint256 root = prod / ratioN == ratioD ? MathEx.floorSqrt(prod) : MathEx.floorSqrt(ratioN) * MathEx.floorSqrt(ratioD); uint256 sum = ratioN.add(ratioD); // the arithmetic below is safe because `x + y >= sqrt(x * y) * 2` if (sum % 2 == 0) { sum /= 2; return Fraction({ n: sum - root, d: sum }); } return Fraction({ n: sum - root * 2, d: sum }); } /** * @dev returns the protection level based on the timestamp and protection delays * * @param addTimestamp time at which the liquidity was added * @param removeTimestamp time at which the liquidity is removed * * @return protection level (as a ratio) */ function protectionLevel(uint256 addTimestamp, uint256 removeTimestamp) internal view returns (Fraction memory) { uint256 timeElapsed = removeTimestamp.sub(addTimestamp); uint256 minProtectionDelay = _settings.minProtectionDelay(); uint256 maxProtectionDelay = _settings.maxProtectionDelay(); if (timeElapsed < minProtectionDelay) { return Fraction({ n: 0, d: 1 }); } if (timeElapsed >= maxProtectionDelay) { return Fraction({ n: 1, d: 1 }); } return Fraction({ n: timeElapsed, d: maxProtectionDelay }); } /** * @dev returns the compensation amount based on the impermanent loss and the protection level * * @param amount protected amount in units of the reserve token * @param total amount plus fee in units of the reserve token * @param loss protection level (as a ratio between 0 and 1) * @param level impermanent loss (as a ratio between 0 and 1) * * @return compensation amount */ function compensationAmount( uint256 amount, uint256 total, Fraction memory loss, Fraction memory level ) internal pure returns (uint256) { uint256 levelN = level.n.mul(amount); uint256 levelD = level.d; uint256 maxVal = MathEx.max(MathEx.max(levelN, levelD), total); (uint256 lossN, uint256 lossD) = MathEx.reducedRatio(loss.n, loss.d, MAX_UINT256 / maxVal); return total.mul(lossD.sub(lossN)).div(lossD).add(lossN.mul(levelN).div(lossD.mul(levelD))); } function networkCompensation( uint256 targetAmount, uint256 baseAmount, PackedRates memory packedRates ) internal view returns (uint256) { if (targetAmount <= baseAmount) { return 0; } // calculate the delta in network tokens uint256 delta = (targetAmount - baseAmount).mul(packedRates.removeAverageRateN).div(packedRates.removeAverageRateD); // the delta might be very small due to precision loss // in which case no compensation will take place (gas optimization) if (delta >= _settings.minNetworkCompensation()) { return delta; } return 0; } // utility to mint network tokens function mintNetworkTokens( address owner, IConverterAnchor poolAnchor, uint256 amount ) private { _systemStore.incNetworkTokensMinted(poolAnchor, amount); _networkTokenGovernance.mint(owner, amount); } // utility to burn network tokens function burnNetworkTokens(IConverterAnchor poolAnchor, uint256 amount) private { _systemStore.decNetworkTokensMinted(poolAnchor, amount); _networkTokenGovernance.burn(amount); } /** * @dev notify event subscribers on adding liquidity * * @param provider liquidity provider * @param poolToken pool token * @param reserveToken reserve token * @param poolAmount amount of pool tokens to protect * @param reserveAmount amount of reserve tokens to protect */ function notifyEventSubscribersOnAddingLiquidity( address provider, IDSToken poolToken, IReserveToken reserveToken, uint256 poolAmount, uint256 reserveAmount ) private { address[] memory subscribers = _settings.subscribers(); uint256 length = subscribers.length; for (uint256 i = 0; i < length; i++) { ILiquidityProvisionEventsSubscriber(subscribers[i]).onAddingLiquidity( provider, poolToken, reserveToken, poolAmount, reserveAmount ); } } /** * @dev notify event subscribers on removing liquidity * * @param id position id * @param provider liquidity provider * @param poolToken pool token * @param reserveToken reserve token * @param poolAmount amount of pool tokens to protect * @param reserveAmount amount of reserve tokens to protect */ function notifyEventSubscribersOnRemovingLiquidity( uint256 id, address provider, IDSToken poolToken, IReserveToken reserveToken, uint256 poolAmount, uint256 reserveAmount ) private { address[] memory subscribers = _settings.subscribers(); uint256 length = subscribers.length; for (uint256 i = 0; i < length; i++) { ILiquidityProvisionEventsSubscriber(subscribers[i]).onRemovingLiquidity( id, provider, poolToken, reserveToken, poolAmount, reserveAmount ); } } // utility to get the reserve balances function converterReserveBalances( IConverter converter, IReserveToken reserveToken1, IReserveToken reserveToken2 ) private view returns (uint256, uint256) { return (converter.getConnectorBalance(reserveToken1), converter.getConnectorBalance(reserveToken2)); } // utility to get the other reserve function converterOtherReserve(IConverter converter, IReserveToken thisReserve) private view returns (IReserveToken) { IReserveToken otherReserve = converter.connectorTokens(0); return otherReserve != thisReserve ? otherReserve : converter.connectorTokens(1); } // utility to get the owner function ownedBy(IOwned owned) private view returns (address) { return owned.owner(); } /** * @dev returns whether the provided reserve token is the network token * * @return whether the provided reserve token is the network token */ function isNetworkToken(IReserveToken reserveToken) private view returns (bool) { return address(reserveToken) == address(_networkToken); } }
error message binary size optimization
function _addLiquidityEnabled(IConverterAnchor poolAnchor, IReserveToken reserveToken) internal view { require(!_settings.addLiquidityDisabled(poolAnchor, reserveToken), "ERR_ADD_LIQUIDITY_DISABLED"); }
1,086,331
// SPDX-License-Identifier: MIT pragma solidity 0.7.4; import "./TellorStake.sol"; import "./TellorGetters.sol"; import "./Utilities.sol"; import "./ITellor.sol"; import "./SafeMath.sol"; /** @author Tellor Inc. @title Tellor @dev Main functionality for Tellor Oracle system **/ contract Tellor is TellorStake,Utilities { using SafeMath for uint256; /*Events*/ //Emits when a tip is added (asking for this ID to be mined ) event TipAdded( address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips ); //Emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) event NewChallenge( bytes32 indexed _currentChallenge, uint256[5] _currentRequestId, uint256 _difficulty, uint256 _totalTips ); //Emits upon a successful Mine, indicates the blockTime at point of the mine and the value mined event NewValue( uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge ); //Emits upon each mine (5 total) and shows the miner, nonce, and value submitted event NonceSubmitted( address indexed _miner, string _nonce, uint256[5] _requestId, uint256[5] _value, bytes32 indexed _currentChallenge, uint256 _slot ); /*Storage -- constant only*/ address immutable extensionAddress; /*Functions*/ /** * @dev Constructor to set extension address * @param _ext Extension address */ constructor(address _ext) { extensionAddress = _ext; } /** * @dev Add tip to a request ID * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the ID with the highest tip */ function addTip(uint256 _requestId, uint256 _tip) external { require(_requestId != 0, "RequestId is 0"); require(_tip != 0, "Tip should be greater than 0"); uint256 _count = uints[_REQUEST_COUNT] + 1; if (_requestId == _count) { uints[_REQUEST_COUNT] = _count; } else { require(_requestId < _count, "RequestId is not less than count"); } _doBurn(msg.sender, _tip); //Update the information for the request that should be mined next based on the tip submitted _updateOnDeck(_requestId, _tip); emit TipAdded( msg.sender, _requestId, _tip, requestDetails[_requestId].apiUintVars[_TOTAL_TIP] ); } /** * @dev This function allows users to swap old trb tokens for new ones based * on the user's old Tellor balance */ function migrate() external { _migrate(msg.sender); } /** * @dev This is function used by the migrator to help * swap old trb tokens for new ones based on the user's old Tellor balance * @param _destination is the address that will receive tokens * @param _amount is the amount to mint to the user * @param _bypass whether or not to bypass the check if they migrated already */ function migrateFor( address _destination, uint256 _amount, bool _bypass ) external { require(msg.sender == addresses[_DEITY], "not allowed"); _migrateFor(_destination, _amount, _bypass); } /** * @dev This function allows miners to submit their mining solution and data requested * @param _nonce is the mining solution * @param _requestIds are the 5 request ids being mined * @param _values are the 5 values corresponding to the 5 request ids */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestIds, uint256[5] calldata _values ) external { bytes32 _hashMsgSender = keccak256(abi.encode(msg.sender)); require( uints[_hashMsgSender] == 0 || block.timestamp - uints[_hashMsgSender] > 15 minutes, "Miner can only win rewards once per 15 min" ); if (uints[_SLOT_PROGRESS] != 4) { _verifyNonce(_nonce); } uints[_hashMsgSender] = block.timestamp; _submitMiningSolution(_nonce, _requestIds, _values); } /*Internal Functions*/ /** * @dev This is an internal function used by submitMiningSolution and adjusts the difficulty * based on the difference between the target time and how long it took to solve * the previous challenge otherwise it sets it to 1 */ function _adjustDifficulty() internal { // If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge // difficulty up or down by the difference between the target time and how long it took to solve the previous challenge // otherwise it sets it to 1 uint256 timeDiff = block.timestamp - uints[_TIME_OF_LAST_NEW_VALUE]; int256 _change = int256(SafeMath.min(1200, timeDiff)); int256 _diff = int256(uints[_DIFFICULTY]); _change = (_diff * (int256(uints[_TIME_TARGET]) - _change)) / 4000; if (_change == 0) { _change = 1; } uints[_DIFFICULTY] = uint256(SafeMath.max(_diff + _change, 1)); } /** * @dev This is an internal function called by updateOnDeck that gets the min value * @param _data is an array [51] to determine the min from * @return min the min value and it's index in the data array */ function _getMin(uint256[51] memory _data) internal pure returns (uint256 min, uint256 minIndex) { minIndex = _data.length - 1; min = _data[minIndex]; for (uint256 i = _data.length - 2; i > 0; i--) { if (_data[i] < min) { min = _data[i]; minIndex = i; } } } /** * @dev Getter function for the top 5 requests with highest payouts. * This function is used within the newBlock function * @return _requestIds the top 5 requests ids based on tips or the last 5 requests ids mined */ function _getTopRequestIDs() internal view returns (uint256[5] memory _requestIds) { uint256[5] memory _max; uint256[5] memory _index; (_max, _index) = _getMax5(requestQ); for (uint256 i = 0; i < 5; i++) { if (_max[i] != 0) { _requestIds[i] = requestIdByRequestQIndex[_index[i]]; } else { _requestIds[i] = currentMiners[4 - i].value; } } } /** * @dev This is an internal function used by the function migrate that helps to * swap old trb tokens for new ones based on the user's old Tellor balance * @param _user is the msg.sender address of the user to migrate the balance from */ function _migrate(address _user) internal { require(!migrated[_user], "Already migrated"); _doMint(_user, ITellor(addresses[_OLD_TELLOR]).balanceOf(_user)); migrated[_user] = true; } /** * @dev This is an internal function used by the function migrate that helps to * swap old trb tokens for new ones based on a custom amount * @param _destination is the address that will receive tokens * @param _amount is the amount to mint to the user * @param _bypass is true if the migrator contract needs to bypass the migrated = true flag * for users that have already migrated */ function _migrateFor( address _destination, uint256 _amount, bool _bypass ) internal { if (!_bypass) require(!migrated[_destination], "already migrated"); _doMint(_destination, _amount); migrated[_destination] = true; } /** * @dev This is an internal function called by submitMiningSolution and adjusts the difficulty, * sorts and stores the first 5 values received, pays the miners, the dev share and * assigns a new challenge * @param _nonce or solution for the PoW for the current challenge * @param _requestIds array of the current request IDs being mined */ function _newBlock(string memory _nonce, uint256[5] memory _requestIds) internal { Request storage _tblock = requestDetails[uints[_T_BLOCK]]; bytes32 _currChallenge = bytesVars[_CURRENT_CHALLENGE]; uint256 _previousTime = uints[_TIME_OF_LAST_NEW_VALUE]; uint256 _timeOfLastNewValueVar = block.timestamp; uints[_TIME_OF_LAST_NEW_VALUE] = _timeOfLastNewValueVar; //this loop sorts the values and stores the median as the official value uint256[5] memory a; uint256[5] memory b; for (uint256 k = 0; k < 5; k++) { for (uint256 i = 1; i < 5; i++) { uint256 temp = _tblock.valuesByTimestamp[k][i]; address temp2 = _tblock.minersByValue[k][i]; uint256 j = i; while (j > 0 && temp < _tblock.valuesByTimestamp[k][j - 1]) { _tblock.valuesByTimestamp[k][j] = _tblock.valuesByTimestamp[ k ][j - 1]; _tblock.minersByValue[k][j] = _tblock.minersByValue[k][ j - 1 ]; j--; } if (j < i) { _tblock.valuesByTimestamp[k][j] = temp; _tblock.minersByValue[k][j] = temp2; } } Request storage _request = requestDetails[_requestIds[k]]; //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number a = _tblock.valuesByTimestamp[k]; _request.finalValues[_timeOfLastNewValueVar] = a[2]; b[k] = a[2]; _request.minersByValue[_timeOfLastNewValueVar] = _tblock .minersByValue[k]; _request.valuesByTimestamp[_timeOfLastNewValueVar] = _tblock .valuesByTimestamp[k]; delete _tblock.minersByValue[k]; delete _tblock.valuesByTimestamp[k]; _request.requestTimestamps.push(_timeOfLastNewValueVar); _request.minedBlockNum[_timeOfLastNewValueVar] = block.number; _request.apiUintVars[_TOTAL_TIP] = 0; } emit NewValue( _requestIds, _timeOfLastNewValueVar, b, uints[_CURRENT_TOTAL_TIPS], _currChallenge ); //add timeOfLastValue to the newValueTimestamps array newValueTimestamps.push(_timeOfLastNewValueVar); address[5] memory miners = requestDetails[_requestIds[0]].minersByValue[ _timeOfLastNewValueVar ]; //pay Miners Rewards _payReward(miners, _previousTime); uints[_T_BLOCK]++; uint256[5] memory _topId = _getTopRequestIDs(); for (uint256 i = 0; i < 5; i++) { currentMiners[i].value = _topId[i]; requestQ[ requestDetails[_topId[i]].apiUintVars[_REQUEST_Q_POSITION] ] = 0; uints[_CURRENT_TOTAL_TIPS] += requestDetails[_topId[i]].apiUintVars[ _TOTAL_TIP ]; } _currChallenge = keccak256( abi.encode(_nonce, _currChallenge, blockhash(block.number - 1)) ); bytesVars[_CURRENT_CHALLENGE] = _currChallenge; // Save hash for next proof emit NewChallenge( _currChallenge, _topId, uints[_DIFFICULTY], uints[_CURRENT_TOTAL_TIPS] ); } /** * @dev This is an internal function used by submitMiningSolution to * calculate and pay rewards to miners * @param miners are the 5 miners to reward * @param _previousTime is the previous mine time based on the 4th entry */ function _payReward(address[5] memory miners, uint256 _previousTime) internal { //_timeDiff is how many seconds passed since last block uint256 _timeDiff = block.timestamp - _previousTime; uint256 reward = (_timeDiff * uints[_CURRENT_REWARD]) / 300; uint256 _tip = uints[_CURRENT_TOTAL_TIPS] / 10; uint256 _devShare = reward / 2; _doMint(miners[0], reward + _tip); _doMint(miners[1], reward + _tip); _doMint(miners[2], reward + _tip); _doMint(miners[3], reward + _tip); _doMint(miners[4], reward + _tip); _doMint(addresses[_OWNER], _devShare); uints[_CURRENT_TOTAL_TIPS] = 0; } /** * @dev This is an internal function used by submitMiningSolution to allow miners to submit * their mining solution and data requested. It checks the miner is staked, has not * won in the last 15 min, and checks they are submitting all the correct requestids * @param _nonce is the mining solution * @param _requestIds are the 5 request ids being mined * @param _values are the 5 values corresponding to the 5 request ids */ function _submitMiningSolution( string memory _nonce, uint256[5] memory _requestIds, uint256[5] memory _values ) internal { bytes32 _hashMsgSender = keccak256(abi.encode(msg.sender)); require( stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker" ); require( _requestIds[0] == currentMiners[0].value, "Request ID is wrong" ); require( _requestIds[1] == currentMiners[1].value, "Request ID is wrong" ); require( _requestIds[2] == currentMiners[2].value, "Request ID is wrong" ); require( _requestIds[3] == currentMiners[3].value, "Request ID is wrong" ); require( _requestIds[4] == currentMiners[4].value, "Request ID is wrong" ); uints[_hashMsgSender] = block.timestamp; bytes32 _currChallenge = bytesVars[_CURRENT_CHALLENGE]; uint256 _slotP = uints[_SLOT_PROGRESS]; //Checking and updating Miner Status require( minersByChallenge[_currChallenge][msg.sender] == false, "Miner already submitted the value" ); //Update the miner status to true once they submit a value so they don't submit more than once minersByChallenge[_currChallenge][msg.sender] = true; //Updating Request Request storage _tblock = requestDetails[uints[_T_BLOCK]]; //Assigning directly is cheaper than using a for loop _tblock.valuesByTimestamp[0][_slotP] = _values[0]; _tblock.valuesByTimestamp[1][_slotP] = _values[1]; _tblock.valuesByTimestamp[2][_slotP] = _values[2]; _tblock.valuesByTimestamp[3][_slotP] = _values[3]; _tblock.valuesByTimestamp[4][_slotP] = _values[4]; _tblock.minersByValue[0][_slotP] = msg.sender; _tblock.minersByValue[1][_slotP] = msg.sender; _tblock.minersByValue[2][_slotP] = msg.sender; _tblock.minersByValue[3][_slotP] = msg.sender; _tblock.minersByValue[4][_slotP] = msg.sender; if (_slotP + 1 == 4) { _adjustDifficulty(); } emit NonceSubmitted( msg.sender, _nonce, _requestIds, _values, _currChallenge, _slotP ); if (_slotP + 1 == 5) { //slotProgress has been incremented, but we're using the variable on stack to save gas _newBlock(_nonce, _requestIds); uints[_SLOT_PROGRESS] = 0; } else { uints[_SLOT_PROGRESS]++; } } /** * @dev This function updates the requestQ when addTip are ran * @param _requestId being requested * @param _tip is the tip to add */ function _updateOnDeck(uint256 _requestId, uint256 _tip) internal { Request storage _request = requestDetails[_requestId]; _request.apiUintVars[_TOTAL_TIP] = _request.apiUintVars[_TOTAL_TIP].add( _tip ); if ( currentMiners[0].value == _requestId || currentMiners[1].value == _requestId || currentMiners[2].value == _requestId || currentMiners[3].value == _requestId || currentMiners[4].value == _requestId ) { uints[_CURRENT_TOTAL_TIPS] += _tip; } else { // if the request is not part of the requestQ[51] array // then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array if (_request.apiUintVars[_REQUEST_Q_POSITION] == 0) { uint256 _min; uint256 _index; (_min, _index) = _getMin(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 and map its index information to the requestId and the apiUintVars if (_request.apiUintVars[_TOTAL_TIP] > _min || _min == 0) { requestQ[_index] = _request.apiUintVars[_TOTAL_TIP]; requestDetails[requestIdByRequestQIndex[_index]] .apiUintVars[_REQUEST_Q_POSITION] = 0; requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[_REQUEST_Q_POSITION] = _index; } // else if the requestId is part of the requestQ[51] then update the tip for it } else { requestQ[_request.apiUintVars[_REQUEST_Q_POSITION]] += _tip; } } } /** * @dev This is an internal function used by submitMiningSolution to allows miners to submit * their mining solution and data requested. It checks the miner has submitted a * valid nonce or allows any solution if 15 minutes or more have passed since last * mined values * @param _nonce is the mining solution */ function _verifyNonce(string memory _nonce) internal view { require( uint256( sha256( abi.encodePacked( ripemd160( abi.encodePacked( keccak256( abi.encodePacked( bytesVars[_CURRENT_CHALLENGE], msg.sender, _nonce ) ) ) ) ) ) ) % uints[_DIFFICULTY] == 0 || block.timestamp - uints[_TIME_OF_LAST_NEW_VALUE] >= 15 minutes, "Incorrect nonce for current challenge" ); } /** * @dev The tellor logic does not fit in one contract so it has been split into two: * Tellor and TellorGetters This functions helps delegate calls to the TellorGetters * contract. */ fallback() external { address addr = extensionAddress; (bool result, ) = addr.delegatecall(msg.data); assembly { returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.4; import "./TellorTransfer.sol"; import "./TellorGetters.sol"; import "./Extension.sol"; import "./Utilities.sol"; /** @author Tellor Inc. @title TellorStake @dev Contains the methods related to initiating disputes and * voting on them. * Because of space limitations some functions are currently on the Extensions contract */ contract TellorStake is TellorTransfer { using SafeMath for uint256; using SafeMath for int256; //this belongs to Tellor, not to master uint256 private constant CURRENT_VERSION = 2999; //emitted when a new dispute is initialized event NewDispute( uint256 indexed _disputeId, uint256 indexed _requestId, uint256 _timestamp, address _miner ); //emitted when a new vote happens event Voted( uint256 indexed _disputeID, bool _position, address indexed _voter, uint256 indexed _voteWeight ); /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false/bad value 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 { Request storage _request = requestDetails[_requestId]; require(_request.minedBlockNum[_timestamp] != 0, "Mined block is 0"); require(_minerIndex < 5, "Miner index is wrong"); //_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex //provided by the party initiating the dispute address _miner = _request.minersByValue[_timestamp][_minerIndex]; uints[keccak256(abi.encodePacked(_miner,"DisputeCount"))]++; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp)); //Increase the dispute count by 1 uints[_DISPUTE_COUNT]++; uint256 disputeId = uints[_DISPUTE_COUNT]; //Ensures that a dispute is not already open for the that miner, requestId and timestamp uint256 hashId = disputeIdByDisputeHash[_hash]; if (hashId != 0) { disputesById[disputeId].disputeUintVars[_ORIGINAL_ID] = hashId; } else { require(block.timestamp - _timestamp < 7 days, "Dispute must be started within a week of bad value"); disputeIdByDisputeHash[_hash] = disputeId; hashId = disputeId; } uint256 dispRounds = _updateLastId(disputeId,hashId); uint256 _fee; if (_minerIndex == 2) { requestDetails[_requestId].apiUintVars[_DISPUTE_COUNT] = requestDetails[_requestId].apiUintVars[_DISPUTE_COUNT] + 1; //update dispute fee for this case _fee = uints[_STAKE_AMOUNT] * requestDetails[_requestId].apiUintVars[_DISPUTE_COUNT]; } else { _fee = uints[_DISPUTE_FEE] * dispRounds; } //maps the dispute to the Dispute struct disputesById[disputeId].hash = _hash; disputesById[disputeId].isPropFork = false; disputesById[disputeId].reportedMiner = _miner; disputesById[disputeId].reportingParty = msg.sender; disputesById[disputeId].proposedForkAddress = address(0); disputesById[disputeId].executed = false; disputesById[disputeId].disputeVotePassed = false; disputesById[disputeId].tally = 0; //Saves all the dispute variables for the disputeId disputesById[disputeId].disputeUintVars[_REQUEST_ID] = _requestId; disputesById[disputeId].disputeUintVars[_TIMESTAMP] = _timestamp; disputesById[disputeId].disputeUintVars[_VALUE] = _request .valuesByTimestamp[_timestamp][_minerIndex]; disputesById[disputeId].disputeUintVars[_MIN_EXECUTION_DATE] = block.timestamp + 2 days * dispRounds; disputesById[disputeId].disputeUintVars[_BLOCK_NUMBER] = block.number; disputesById[disputeId].disputeUintVars[_MINER_SLOT] = _minerIndex; disputesById[disputeId].disputeUintVars[_FEE] = _fee; _doTransfer(msg.sender, address(this), _fee); //Values are sorted as they come in and the official value is the median of the first five //So the "official value" miner is always minerIndex==2. If the official value is being //disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute if (_minerIndex == 2) { _request.inDispute[_timestamp] = true; _request.finalValues[_timestamp] = 0; } stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId, _requestId, _timestamp, _miner); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external { require(uints[_LOCK] == 0, "no rentrancy"); uints[_LOCK] = 1; _verify(_propNewTellorAddress); uints[_LOCK] = 0; bytes32 _hash = keccak256(abi.encode(_propNewTellorAddress)); uints[_DISPUTE_COUNT]++; uint256 disputeId = uints[_DISPUTE_COUNT]; if (disputeIdByDisputeHash[_hash] != 0) { disputesById[disputeId].disputeUintVars[ _ORIGINAL_ID ] = disputeIdByDisputeHash[_hash]; } else { disputeIdByDisputeHash[_hash] = disputeId; } uint256 dispRounds = _updateLastId(disputeId,disputeIdByDisputeHash[_hash]); disputesById[disputeId].hash = _hash; disputesById[disputeId].isPropFork = true; // I don't think we need those disputesById[disputeId].reportedMiner = msg.sender; disputesById[disputeId].reportingParty = msg.sender; disputesById[disputeId].proposedForkAddress = _propNewTellorAddress; disputesById[disputeId].tally = 0; _doTransfer(msg.sender, address(this), 100e18 * 2**(dispRounds - 1)); //This is the fork fee (just 100 tokens flat, no refunds. Goes up quickly to dispute a bad vote) disputesById[disputeId].disputeUintVars[_BLOCK_NUMBER] = block.number; disputesById[disputeId].disputeUintVars[_MIN_EXECUTION_DATE] = block.timestamp + 7 days; } /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external { require(_disputeId <= uints[_DISPUTE_COUNT], "dispute does not exist"); uint256 origID = disputeIdByDisputeHash[disputesById[_disputeId].hash]; uint256 lastID = disputesById[origID].disputeUintVars[ keccak256( abi.encode( disputesById[origID].disputeUintVars[_DISPUTE_ROUNDS] ) ) ]; if (lastID == 0) { lastID = origID; } Dispute storage disp = disputesById[origID]; Dispute storage last = disputesById[lastID]; //disputeRounds is increased by 1 so that the _id is not a negative number when it is the first time a dispute is initiated uint256 dispRounds = disp.disputeUintVars[_DISPUTE_ROUNDS]; if (dispRounds == 0) { dispRounds = 1; } uint256 _id; require(disp.disputeUintVars[_PAID] == 0, "already paid out"); require(!disp.isPropFork, "function not callable fork fork proposals"); require(disp.disputeUintVars[_TALLY_DATE] > 0, "vote needs to be tallied"); require( block.timestamp - last.disputeUintVars[_TALLY_DATE] > 1 days, "Time for a follow up dispute hasn't elapsed" ); StakeInfo storage stakes = stakerDetails[disp.reportedMiner]; disp.disputeUintVars[_PAID] = 1; if (last.disputeVotePassed == true) { //Changing the currentStatus and startDate unstakes the reported miner and transfers the stakeAmount stakes.startDate = block.timestamp - (block.timestamp % 86400); //Reduce the staker count uints[_STAKE_COUNT] -= 1; //Decreases the stakerCount since the miner's stake is being slashed uint256 _transferAmount = uints[_STAKE_AMOUNT]; if(balanceOf(disp.reportedMiner) < uints[_STAKE_AMOUNT]){ _transferAmount = balanceOf(disp.reportedMiner); } if (stakes.currentStatus == 4) { stakes.currentStatus = 5; _doTransfer( disp.reportedMiner, disp.reportingParty, _transferAmount ); stakes.currentStatus = 0; } for (uint256 i = 0; i < dispRounds; i++) { _id = disp.disputeUintVars[ keccak256(abi.encode(dispRounds - i)) ]; if (_id == 0) { _id = origID; } Dispute storage disp2 = disputesById[_id]; //transfer fee adjusted based on number of miners if the minerIndex is not 2(official value) _doTransfer( address(this), disp2.reportingParty, disp2.disputeUintVars[_FEE] ); } } else { if(uints[keccak256(abi.encodePacked(last.reportedMiner,"DisputeCount"))] == 1){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = requestDetails[disp.disputeUintVars[_REQUEST_ID]]; if (disp.disputeUintVars[_MINER_SLOT] == 2) { //note we still don't put timestamp back into array (is this an issue? (shouldn't be)) _request.finalValues[disp.disputeUintVars[_TIMESTAMP]] = disp .disputeUintVars[_VALUE]; } if (_request.inDispute[disp.disputeUintVars[_TIMESTAMP]] == true) { _request.inDispute[disp.disputeUintVars[_TIMESTAMP]] = false; } for (uint256 i = 0; i < dispRounds; i++) { _id = disp.disputeUintVars[ keccak256(abi.encode(dispRounds - i)) ]; if (_id != 0) { last = disputesById[_id]; //handling if happens during an upgrade } _doTransfer( address(this), last.reportedMiner, disputesById[_id].disputeUintVars[_FEE] ); } } uints[keccak256(abi.encodePacked(last.reportedMiner,"DisputeCount"))]--; if (disp.disputeUintVars[_MINER_SLOT] == 2) { requestDetails[disp.disputeUintVars[_REQUEST_ID]].apiUintVars[ _DISPUTE_COUNT ]--; } } /** * @dev Used during upgrade process to verify valid Tellor Contract */ function verify() external virtual returns (uint256) { return CURRENT_VERSION; } /** * @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 { require(_disputeId <= uints[_DISPUTE_COUNT], "dispute does not exist"); Dispute storage disp = disputesById[_disputeId]; require(!disp.executed, "the dispute has already been executed"); //Get the voteWeight or the balance of the user at the time/blockNumber the dispute began uint256 voteWeight = balanceOfAt(msg.sender, disp.disputeUintVars[_BLOCK_NUMBER]); //Require that the msg.sender has not voted require(disp.voted[msg.sender] != true, "Sender has already voted"); //Require that the user had a balance >0 at time/blockNumber the dispute began require(voteWeight != 0, "User balance is 0"); //ensures miners that are under dispute cannot vote require( 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[_NUM_OF_VOTES] += 1; //If the user supports the dispute increase the tally for the dispute by the voteWeight //otherwise decrease it if (_supportsDispute) { disp.tally = disp.tally.add(int256(voteWeight)); } else { disp.tally = disp.tally.sub(int256(voteWeight)); } //Let the network kblock.timestamp the user has voted on the dispute and their casted vote emit Voted(_disputeId, _supportsDispute, msg.sender, voteWeight); } /** * @dev Internal function with round checking logic from beginDispute/ proposeFork * @param _disputeId new dispute ID of round * @param _origId original ID of the hash */ function _updateLastId(uint _disputeId,uint _origId) internal returns(uint256 _dispRounds){ _dispRounds = disputesById[_origId].disputeUintVars[_DISPUTE_ROUNDS] + 1; disputesById[_origId].disputeUintVars[_DISPUTE_ROUNDS] = _dispRounds; disputesById[_origId].disputeUintVars[ keccak256(abi.encode(_dispRounds)) ] = _disputeId; if (_disputeId != _origId) { uint256 _lastId = disputesById[_origId].disputeUintVars[keccak256(abi.encode(_dispRounds - 1))]; require( disputesById[_lastId].disputeUintVars[_MIN_EXECUTION_DATE] <= block.timestamp, "Dispute is already open" ); if (disputesById[_lastId].executed) { require( block.timestamp - disputesById[_lastId].disputeUintVars[_TALLY_DATE] <= 1 days, "Time for voting haven't elapsed" ); } } } /** * @dev Used during upgrade process to verify valid Tellor Contract */ function _verify(address _newTellor) internal { (bool success, bytes memory data) = address(_newTellor).call( abi.encodeWithSelector(0xfc735e99, "") //verify() signature ); require( success && abi.decode(data, (uint256)) > CURRENT_VERSION, //we could enforce versioning through this return value, but we're almost in the size limit. "new tellor is invalid" ); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.4; import "./SafeMath.sol"; import "./TellorStorage.sol"; import "./TellorVariables.sol"; import "./Utilities.sol"; /** @author Tellor Inc. @title TellorGetters @dev Getter functions for Tellor Oracle system */ contract TellorGetters is TellorStorage, TellorVariables, Utilities { using SafeMath for uint256; /** * @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 minersByChallenge[_challenge][_miner]; } /** * @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 disputesById[_disputeId].voted[_address]; } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * @return address of the requested variable */ function getAddressVars(bytes32 _data) external view returns (address) { return addresses[_data]; } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * bool executed where true if it has been voted on * bool disputeVotePassed * bool isPropFork true if the dispute is a proposed fork * address of reportedMiner * address of reportingParty * address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ) { Dispute storage disp = disputesById[_disputeId]; return ( disp.hash, disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty, disp.proposedForkAddress, [ disp.disputeUintVars[_REQUEST_ID], disp.disputeUintVars[_TIMESTAMP], disp.disputeUintVars[_VALUE], disp.disputeUintVars[_MIN_EXECUTION_DATE], disp.disputeUintVars[_NUM_OF_VOTES], disp.disputeUintVars[_BLOCK_NUMBER], disp.disputeUintVars[_MINER_SLOT], disp.disputeUintVars[keccak256("quorum")], disp.disputeUintVars[_FEE] ], disp.tally ); } /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId,_timestamp)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256) { return disputeIdByDisputeHash[_hash]; } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disputeId * @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 disputesById[_disputeId].disputeUintVars[_data]; } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submitted and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool) { Request storage _request = requestDetails[_requestId]; if (_request.requestTimestamps.length != 0) { return ( retrieveData( _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(uint256 _requestId, uint256 _timestamp) external view returns (uint256) { return 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( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory) { return requestDetails[_requestId].minersByValue[_timestamp]; } /** * @dev Counts the number of values that have been submitted 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 requestDetails[_requestId].requestTimestamps.length; } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of requestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256) { require(_index <= 50, "RequestQ index is above 50"); return requestIdByRequestQIndex[_index]; } /** * @dev Getter function for the requestQ array * @return the requestQ array */ function getRequestQ() external view returns (uint256[51] memory) { return requestQ; } /** * @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 * in TellorVariables.sol * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256) { return 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(uint256 _requestId) external view returns (uint256, uint256) { Request storage _request = requestDetails[_requestId]; return ( _request.apiUintVars[_REQUEST_Q_POSITION], _request.apiUintVars[_TOTAL_TIP] ); } /** * @dev This function allows users to retrieve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256) { return ( stakerDetails[_staker].currentStatus, stakerDetails[_staker].startDate ); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return address[5] array of 5 addresses of miners that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory) { return 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(uint256 _requestID, uint256 _index) external view returns (uint256) { return requestDetails[_requestID].requestTimestamps[_index]; } /** * @dev Getter for the variables saved under the TellorStorageStruct uints 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 in the TellorVariables contract * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256) { return uints[_data]; } /** * @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 requestDetails[_requestId].inDispute[_timestamp]; } /** * @dev Retrieve value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retrieve data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) public view returns (uint256) { return requestDetails[_requestId].finalValues[_timestamp]; } /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256) { return uints[_TOTAL_SUPPLY]; } /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory) { return "Tellor Tributes"; } /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory) { return "TRB"; } /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8) { return 18; } /** * @dev Getter function for the requestId being mined * returns the currentChallenge, array of requestIDs, difficulty, and the current Tip of the 5 IDs */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _diff, uint256 _tip ) { for (uint256 i = 0; i < 5; i++) { _requestIds[i] = currentMiners[i].value; } return ( bytesVars[_CURRENT_CHALLENGE], _requestIds, uints[_DIFFICULTY], uints[_CURRENT_TOTAL_TIPS] ); } /** * @dev Getter function for next requestIds on queue/request with highest payouts at time the function is called */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck) { idsOnDeck = getTopRequestIDs(); for (uint256 i = 0; i < 5; i++) { tipsOnDeck[i] = requestDetails[idsOnDeck[i]].apiUintVars[ _TOTAL_TIP ]; } } /** * @dev Getter function for the top 5 requests with highest payouts. This function is used within the getNewVariablesOnDeck function */ function getTopRequestIDs() public view returns (uint256[5] memory _requestIds) { uint256[5] memory _max; uint256[5] memory _index; (_max, _index) = _getMax5(requestQ); for (uint256 i = 0; i < 5; i++) { if (_max[i] != 0) { _requestIds[i] = requestIdByRequestQIndex[_index[i]]; } else { _requestIds[i] = currentMiners[4 - i].value; } } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.4; /** @author Tellor Inc. @title Utilities @dev 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 */ contract Utilities { /** * @dev This is an internal function called by updateOnDeck that gets the top 5 values * @param data is an array [51] to determine the top 5 values from * @return max the top 5 values and their index values in the data array */ function _getMax5(uint256[51] memory data) internal pure returns (uint256[5] memory max, uint256[5] memory maxIndex) { uint256 min5 = data[1]; uint256 minI = 0; for (uint256 j = 0; j < 5; j++) { max[j] = data[j + 1]; //max[0]=data[1] maxIndex[j] = j + 1; //maxIndex[0]= 1 if (max[j] < min5) { min5 = max[j]; minI = j; } } for (uint256 i = 6; i < data.length; i++) { if (data[i] > min5) { max[minI] = data[i]; maxIndex[minI] = i; min5 = data[i]; for (uint256 j = 0; j < 5; j++) { if (max[j] < min5) { min5 = max[j]; minI = j; } } } } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.4; /** @author Tellor Inc. @title ITellor @dev This contract holds the interface for all Tellor functions **/ interface ITellor { /*Events*/ event NewTellorAddress(address _newTellor); event NewDispute( uint256 indexed _disputeId, uint256 indexed _requestId, uint256 _timestamp, address _miner ); event Voted( uint256 indexed _disputeID, bool _position, address indexed _voter, uint256 indexed _voteWeight ); event DisputeVoteTallied( uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _passed ); event TipAdded( address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips ); event NewChallenge( bytes32 indexed _currentChallenge, uint256[5] _currentRequestId, uint256 _difficulty, uint256 _totalTips ); event NewValue( uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge ); event NonceSubmitted( address indexed _miner, string _nonce, uint256[5] _requestId, uint256[5] _value, bytes32 indexed _currentChallenge, uint256 _slot ); 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 event Approval( address indexed _owner, address indexed _spender, uint256 _value ); event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event /*Functions -- master*/ function changeDeity(address _newDeity) external; function changeOwner(address _newOwner) external; function changeTellorContract(address _tellorContract) external; /*Functions -- Extension*/ function depositStake() external; function requestStakingWithdraw() external; function tallyVotes(uint256 _disputeId) external; function updateMinDisputeFee() external; function updateTellor(uint256 _disputeId) external; function withdrawStake() external; /*Functions -- Tellor*/ function addTip(uint256 _requestId, uint256 _tip) external; function changeExtension(address _extension) external; function changeMigrator(address _migrator) external; function migrate() external; function migrateFor( address _destination, uint256 _amount, bool _bypass ) external; function migrateForBatch( address[] calldata _destination, uint256[] calldata _amount ) external; function migrateFrom( address _origin, address _destination, uint256 _amount, bool _bypass ) external; function migrateFromBatch( address[] calldata _origin, address[] calldata _destination, uint256[] calldata _amount ) external; function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestIds, uint256[5] calldata _values ) external; /*Functions -- TellorGetters*/ function didMine(bytes32 _challenge, address _miner) external view returns (bool); function didVote(uint256 _disputeId, address _address) external view returns (bool); function getAddressVars(bytes32 _data) external view returns (address); function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); function getLastNewValue() external view returns (uint256, bool); function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); function getRequestQ() external view returns (uint256[51] memory); function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); function getRequestVars(uint256 _requestId) external view returns (uint256, uint256); function getStakerInfo(address _staker) external view returns (uint256, uint256); function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); function getUintVar(bytes32 _data) external view returns (uint256); function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); function totalSupply() external view returns (uint256); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficulty, uint256 _tip ); function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck ); function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /*Functions -- TellorStake*/ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; function proposeFork(address _propNewTellorAddress) external; function unlockDisputeFee(uint256 _disputeId) external; function verify() external returns (uint256); function vote(uint256 _disputeId, bool _supportsDispute) external; /*Functions -- TellorTransfer*/ function approve(address _spender, uint256 _amount) external returns (bool); function allowance(address _user, address _spender) external view returns (uint256); function allowedToTrade(address _user, uint256 _amount) external view returns (bool); function balanceOf(address _user) external view returns (uint256); function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); function transfer(address _to, uint256 _amount) external returns (bool); function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); //Test Functions function theLazyCoon(address _address, uint256 _amount) external; function testSubmitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; function manuallySetDifficulty(uint256 _diff) external; function testgetMax5(uint256[51] memory requests) external view returns (uint256[5] memory _max, uint256[5] memory _index); } // SPDX-License-Identifier: MIT pragma solidity 0.7.4; /** @author Tellor Inc. @title SafeMath @dev 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); } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.4; import "./SafeMath.sol"; import "./TellorStorage.sol"; import "./TellorVariables.sol"; /** @author Tellor Inc. @title TellorTransfer @dev Contains the methods related to transfers and ERC20, its storage and hashes of tellor variables * that are used to save gas on transactions. */ contract TellorTransfer is TellorStorage, TellorVariables { using SafeMath for uint256; /*Events*/ event Approval( address indexed _owner, address indexed _spender, uint256 _value ); //ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event /*Functions*/ /** * @dev Getter function for remaining spender balance * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) public view returns (uint256) { return _allowances[_user][_spender]; } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(address _user, uint256 _amount) public view returns (bool) { if ( stakerDetails[_user].currentStatus != 0 && stakerDetails[_user].currentStatus < 5 ) { //Subtracts the stakeAmount from balance if the _user is staked if (balanceOf(_user).sub(uints[_STAKE_AMOUNT]) >= _amount) { return true; } return false; } return (balanceOf(_user) >= _amount); } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender approved successfully */ function approve(address _spender, uint256 _amount) public returns (bool) { require(_spender != address(0), "ERC20: approve to the zero address"); _allowances[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @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(address _user) public view returns (uint256) { return balanceOfAt(_user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(address _user, uint256 _blockNumber) public view returns (uint256) { TellorStorage.Checkpoint[] storage checkpoints = balances[_user]; if ( checkpoints.length == 0 || checkpoints[0].fromBlock > _blockNumber ) { return 0; } else { if (_blockNumber >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length - 2; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock == _blockNumber) { return checkpoints[mid].value; } else if (checkpoints[mid].fromBlock < _blockNumber) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } } /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send */ function transfer(address _to, uint256 _amount) public returns (bool success) { _doTransfer(msg.sender, _to, _amount); return true; } /** * @notice Send _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _amount ) public returns (bool success) { require( _allowances[_from][msg.sender] >= _amount, "Allowance is wrong" ); _allowances[_from][msg.sender] -= _amount; _doTransfer(_from, _to, _amount); return true; } /*Internal Functions*/ /** * @dev Completes transfers by updating the balances on the current block number * and ensuring the amount does not contain tokens staked for mining * @param _from address to transfer from * @param _to address to transfer to * @param _amount to transfer */ function _doTransfer( address _from, address _to, uint256 _amount ) internal { require(_amount != 0, "Tried to send non-positive amount"); require(_to != address(0), "Receiver is 0 address"); require( allowedToTrade(_from, _amount), "Should have sufficient balance to trade" ); uint128 previousBalance = uint128(balanceOf(_from)); uint128 _sizedAmount = uint128(_amount); _updateBalanceAtNow(_from, previousBalance - _sizedAmount); previousBalance = uint128(balanceOf(_to)); require( previousBalance + _sizedAmount >= previousBalance, "Overflow happened" ); // Check for overflow _updateBalanceAtNow(_to, previousBalance + _sizedAmount); emit Transfer(_from, _to, _amount); } /** * @dev Helps swap the old Tellor contract Tokens to the new one * @param _to is the adress to send minted amount to * @param _amount is the amount of TRB to send */ function _doMint(address _to, uint256 _amount) internal { require(_amount != 0, "Tried to mint non-positive amount"); require(_to != address(0), "Receiver is 0 address"); uint128 previousBalance = uint128(balanceOf(_to)); uint128 _sizedAmount = uint128(_amount); require( previousBalance + _sizedAmount >= previousBalance, "Overflow happened" ); uint256 previousSupply = uints[_TOTAL_SUPPLY]; require( previousSupply + _amount >= previousSupply, "Overflow happened" ); uints[_TOTAL_SUPPLY] += _amount; _updateBalanceAtNow(_to, previousBalance + _sizedAmount); emit Transfer(address(0), _to, _amount); } /** * @dev Helps burn TRB Tokens * @param _from is the adress to burn or remove TRB amount * @param _amount is the amount of TRB to burn */ function _doBurn(address _from, uint256 _amount) internal { if (_amount == 0) return; require( allowedToTrade(_from, _amount), "Should have sufficient balance to trade" ); uint128 previousBalance = uint128(balanceOf(_from)); uint128 _sizedAmount = uint128(_amount); require( previousBalance - _sizedAmount <= previousBalance, "Overflow happened" ); uint256 previousSupply = uints[_TOTAL_SUPPLY]; require( previousSupply - _amount <= previousSupply, "Overflow happened" ); _updateBalanceAtNow(_from, previousBalance - _sizedAmount); uints[_TOTAL_SUPPLY] -= _amount; } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param _value is the new balance */ function _updateBalanceAtNow(address _user, uint128 _value) internal { Checkpoint[] storage checkpoints = balances[_user]; if ( checkpoints.length == 0 || checkpoints[checkpoints.length - 1].fromBlock != block.number ) { checkpoints.push( TellorStorage.Checkpoint({ fromBlock: uint128(block.number), value: _value }) ); } else { TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = _value; } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.4; import "./SafeMath.sol"; import "./TellorGetters.sol"; import "./TellorVariables.sol"; import "./Utilities.sol"; /** @author Tellor Inc. @title Extension @dev This contract holds staking functions, tallyVotes and updateDisputeFee * Because of space limitations and will be consolidated in future iterations **/ contract Extension is TellorGetters { using SafeMath for uint256; /*Events*/ //emitted upon dispute tally event DisputeVoteTallied( uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _passed ); event StakeWithdrawn(address indexed _sender); //Emits when a staker is block.timestamp no longer staked event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period event NewStake(address indexed _sender); //Emits upon new staker event NewTellorAddress(address _newTellor); /*Functions*/ /** * @dev This function allows miners to deposit their stake. */ function depositStake() external{ _newStake(msg.sender); updateMinDisputeFee(); } /** * @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() external { StakeInfo storage stakes = stakerDetails[msg.sender]; //Require that the miner is staked require(stakes.currentStatus == 1, "Miner is not staked"); //Change the miner staked to locked to be withdrawStake stakes.currentStatus = 2; //Change the startDate to block.timestamp since the lock up period begins block.timestamp //and the miner can only withdraw 7 days later from block.timestamp(check the withdraw function) stakes.startDate = block.timestamp - (block.timestamp % 86400); //Reduce the staker count uints[_STAKE_COUNT] -= 1; //Update the minimum dispute fee that is based on the number of stakers updateMinDisputeFee(); emit StakeWithdrawRequested(msg.sender); } /** * @dev tallies the votes and locks the stake disbursement(currentStatus = 4) if the vote passes * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external { Dispute storage disp = disputesById[_disputeId]; //Ensure this has not already been executed/tallied require(disp.executed == false, "Dispute has been already executed"); //Ensure that the vote has been open long enough require( block.timestamp >= disp.disputeUintVars[_MIN_EXECUTION_DATE], "Time for voting haven't elapsed" ); //Ensure that it's a valid disputeId require( disp.reportingParty != address(0), "reporting Party is address 0" ); int256 _tally = disp.tally; if (_tally > 0) { //If the vote is not a proposed fork if (disp.isPropFork == false) { //Set the dispute state to passed/true disp.disputeVotePassed = true; //Ensure the time for voting has elapsed StakeInfo storage stakes = stakerDetails[disp.reportedMiner]; //If the vote for disputing a value is successful(disp.tally >0) then unstake the reported if (stakes.currentStatus == 3) { stakes.currentStatus = 4; } } else if (uint256(_tally) >= ((uints[_TOTAL_SUPPLY] * 5) / 100)) { disp.disputeVotePassed = true; } } disp.disputeUintVars[_TALLY_DATE] = block.timestamp; disp.executed = true; emit DisputeVoteTallied( _disputeId, _tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed ); } /** * @dev This function updates the minimum dispute fee as a function of the amount * of staked miners */ function updateMinDisputeFee() public { uint256 _stakeAmt = uints[_STAKE_AMOUNT]; uint256 _trgtMiners = uints[_TARGET_MINERS]; uints[_DISPUTE_FEE] = SafeMath.max( 15e18, (_stakeAmt - ((_stakeAmt * (SafeMath.min(_trgtMiners, uints[_STAKE_COUNT]) * 1000)) / _trgtMiners) / 1000) ); } /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external { bytes32 _hash = disputesById[_disputeId].hash; uint256 origID = disputeIdByDisputeHash[_hash]; //this checks the "lastID" or the most recent if this is a multiple dispute case uint256 lastID = disputesById[origID].disputeUintVars[ keccak256( abi.encode( disputesById[origID].disputeUintVars[_DISPUTE_ROUNDS] ) ) ]; TellorStorage.Dispute storage disp = disputesById[lastID]; require(disp.isPropFork, "must be a fork proposal"); require( disp.disputeUintVars[_FORK_EXECUTED] == 0, "update Tellor has already been run" ); require(disp.disputeVotePassed == true, "vote needs to pass"); require(disp.disputeUintVars[_TALLY_DATE] > 0, "vote needs to be tallied"); require( block.timestamp - disp.disputeUintVars[_TALLY_DATE] > 1 days, "Time for voting for further disputes has not passed" ); disp.disputeUintVars[_FORK_EXECUTED] = 1; address _newTellor =disp.proposedForkAddress; addresses[_TELLOR_CONTRACT] = _newTellor; assembly { sstore(_EIP_SLOT, _newTellor) } emit NewTellorAddress(_newTellor); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting * period from request */ function withdrawStake() external { StakeInfo storage stakes = 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( block.timestamp - (block.timestamp % 86400) - stakes.startDate >= 7 days, "7 days didn't pass" ); require( stakes.currentStatus == 2, "Miner was not locked for withdrawal" ); stakes.currentStatus = 0; emit StakeWithdrawn(msg.sender); } /** * @dev This internal function is used the depositStake function to successfully stake miners. * The function updates their status/state and status start date so they are locked it so they can't withdraw * and updates the number of stakers in the system. * @param _staker the address of the new staker */ function _newStake(address _staker) internal { require( balances[_staker][balances[_staker].length - 1].value >= uints[_STAKE_AMOUNT], "Balance is lower than stake amount" ); //Ensure they can only stake if they are not currently staked or if their stake time frame has ended //and they are currently locked for withdraw require( stakerDetails[_staker].currentStatus == 0 || stakerDetails[_staker].currentStatus == 2, "Miner is in the wrong state" ); uints[_STAKE_COUNT] += 1; stakerDetails[_staker] = StakeInfo({ currentStatus: 1, startDate: block.timestamp//this resets their stake start date to now }); emit NewStake(_staker); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.4; /** @author Tellor Inc. @title TellorStorage @dev Contains all the variables/structs used by Tellor */ contract TellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint256 value; address miner; } struct Dispute { bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int256 tally; //current tally of votes for - against measure bool executed; //is the dispute settled bool disputeVotePassed; //did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress; //new fork address (if fork proposal) mapping(bytes32 => uint256) disputeUintVars; mapping(address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute 4=ReadyForUnlocking 5=Unlocked uint256 startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock; // fromBlock is the block number that the value was generated from uint128 value; // value is the amount of tokens at a specific block number } struct Request { uint256[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint256) apiUintVars; 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; } uint256[51] requestQ; //uint50 array of the top50 requests by payment amount uint256[] public newValueTimestamps; //array of all timestamps requested //This is a boolean that tells you if a given challenge has been completed by a given miner mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint256 => Dispute) public disputesById; //disputeId=> Dispute details mapping(bytes32 => uint256) public requestIdByQueryHash; // api bytes32 gets an id = to count of requests array mapping(bytes32 => uint256) public disputeIdByDisputeHash; //maps a hash to an ID for each dispute mapping(bytes32 => mapping(address => bool)) public minersByChallenge; Details[5] public currentMiners; //This struct is for organizing the five mined values to find the median mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info mapping(uint256 => Request) requestDetails; mapping(bytes32 => uint256) public uints; mapping(bytes32 => address) public addresses; mapping(bytes32 => bytes32) public bytesVars; //ERC20 storage mapping(address => Checkpoint[]) public balances; mapping(address => mapping(address => uint256)) public _allowances; //Migration storage mapping(address => bool) public migrated; } // SPDX-License-Identifier: MIT pragma solidity 0.7.4; /** @author Tellor Inc. @title TellorVariables @dev Helper contract to store hashes of variables */ contract TellorVariables { bytes32 constant _BLOCK_NUMBER = 0x4b4cefd5ced7569ef0d091282b4bca9c52a034c56471a6061afd1bf307a2de7c; //keccak256("_BLOCK_NUMBER"); bytes32 constant _CURRENT_CHALLENGE = 0xd54702836c9d21d0727ffacc3e39f57c92b5ae0f50177e593bfb5ec66e3de280; //keccak256("_CURRENT_CHALLENGE"); bytes32 constant _CURRENT_REQUESTID = 0xf5126bb0ac211fbeeac2c0e89d4c02ac8cadb2da1cfb27b53c6c1f4587b48020; //keccak256("_CURRENT_REQUESTID"); bytes32 constant _CURRENT_REWARD = 0xd415862fd27fb74541e0f6f725b0c0d5b5fa1f22367d9b78ec6f61d97d05d5f8; //keccak256("_CURRENT_REWARD"); bytes32 constant _CURRENT_TOTAL_TIPS = 0x09659d32f99e50ac728058418d38174fe83a137c455ff1847e6fb8e15f78f77a; //keccak256("_CURRENT_TOTAL_TIPS"); bytes32 constant _DEITY = 0x5fc094d10c65bc33cc842217b2eccca0191ff24148319da094e540a559898961; //keccak256("_DEITY"); bytes32 constant _DIFFICULTY = 0xf758978fc1647996a3d9992f611883adc442931dc49488312360acc90601759b; //keccak256("_DIFFICULTY"); bytes32 constant _DISPUTE_COUNT = 0x310199159a20c50879ffb440b45802138b5b162ec9426720e9dd3ee8bbcdb9d7; //keccak256("_DISPUTE_COUNT"); bytes32 constant _DISPUTE_FEE = 0x675d2171f68d6f5545d54fb9b1fb61a0e6897e6188ca1cd664e7c9530d91ecfc; //keccak256("_DISPUTE_FEE"); bytes32 constant _DISPUTE_ROUNDS = 0x6ab2b18aafe78fd59c6a4092015bddd9fcacb8170f72b299074f74d76a91a923; //keccak256("_DISPUTE_ROUNDS"); bytes32 constant _EXTENSION = 0x2b2a1c876f73e67ebc4f1b08d10d54d62d62216382e0f4fd16c29155818207a4; //keccak256("_EXTENSION"); bytes32 constant _FEE = 0x1da95f11543c9b03927178e07951795dfc95c7501a9d1cf00e13414ca33bc409; //keccak256("_FEE"); bytes32 constant _FORK_EXECUTED = 0xda571dfc0b95cdc4a3835f5982cfdf36f73258bee7cb8eb797b4af8b17329875; //keccak256("_FORK_EXECUTED"); bytes32 constant _LOCK = 0xd051321aa26ce60d202f153d0c0e67687e975532ab88ce92d84f18e39895d907; bytes32 constant _MIGRATOR = 0xc6b005d45c4c789dfe9e2895b51df4336782c5ff6bd59a5c5c9513955aa06307; //keccak256("_MIGRATOR"); bytes32 constant _MIN_EXECUTION_DATE = 0x46f7d53798d31923f6952572c6a19ad2d1a8238d26649c2f3493a6d69e425d28; //keccak256("_MIN_EXECUTION_DATE"); bytes32 constant _MINER_SLOT = 0x6de96ee4d33a0617f40a846309c8759048857f51b9d59a12d3c3786d4778883d; //keccak256("_MINER_SLOT"); bytes32 constant _NUM_OF_VOTES = 0x1da378694063870452ce03b189f48e04c1aa026348e74e6c86e10738514ad2c4; //keccak256("_NUM_OF_VOTES"); bytes32 constant _OLD_TELLOR = 0x56e0987db9eaec01ed9e0af003a0fd5c062371f9d23722eb4a3ebc74f16ea371; //keccak256("_OLD_TELLOR"); bytes32 constant _ORIGINAL_ID = 0xed92b4c1e0a9e559a31171d487ecbec963526662038ecfa3a71160bd62fb8733; //keccak256("_ORIGINAL_ID"); bytes32 constant _OWNER = 0x7a39905194de50bde334d18b76bbb36dddd11641d4d50b470cb837cf3bae5def; //keccak256("_OWNER"); bytes32 constant _PAID = 0x29169706298d2b6df50a532e958b56426de1465348b93650fca42d456eaec5fc; //keccak256("_PAID"); bytes32 constant _PENDING_OWNER = 0x7ec081f029b8ac7e2321f6ae8c6a6a517fda8fcbf63cabd63dfffaeaafa56cc0; //keccak256("_PENDING_OWNER"); bytes32 constant _REQUEST_COUNT = 0x3f8b5616fa9e7f2ce4a868fde15c58b92e77bc1acd6769bf1567629a3dc4c865; //keccak256("_REQUEST_COUNT"); bytes32 constant _REQUEST_ID = 0x9f47a2659c3d32b749ae717d975e7962959890862423c4318cf86e4ec220291f; //keccak256("_REQUEST_ID"); bytes32 constant _REQUEST_Q_POSITION = 0xf68d680ab3160f1aa5d9c3a1383c49e3e60bf3c0c031245cbb036f5ce99afaa1; //keccak256("_REQUEST_Q_POSITION"); bytes32 constant _SLOT_PROGRESS = 0xdfbec46864bc123768f0d134913175d9577a55bb71b9b2595fda21e21f36b082; //keccak256("_SLOT_PROGRESS"); bytes32 constant _STAKE_AMOUNT = 0x5d9fadfc729fd027e395e5157ef1b53ef9fa4a8f053043c5f159307543e7cc97; //keccak256("_STAKE_AMOUNT"); bytes32 constant _STAKE_COUNT = 0x10c168823622203e4057b65015ff4d95b4c650b308918e8c92dc32ab5a0a034b; //keccak256("_STAKE_COUNT"); bytes32 constant _T_BLOCK = 0xf3b93531fa65b3a18680d9ea49df06d96fbd883c4889dc7db866f8b131602dfb; //keccak256("_T_BLOCK"); bytes32 constant _TALLY_DATE = 0xf9e1ae10923bfc79f52e309baf8c7699edb821f91ef5b5bd07be29545917b3a6; //keccak256("_TALLY_DATE"); bytes32 constant _TARGET_MINERS = 0x0b8561044b4253c8df1d9ad9f9ce2e0f78e4bd42b2ed8dd2e909e85f750f3bc1; //keccak256("_TARGET_MINERS"); bytes32 constant _TELLOR_CONTRACT = 0x0f1293c916694ac6af4daa2f866f0448d0c2ce8847074a7896d397c961914a08; //keccak256("_TELLOR_CONTRACT"); bytes32 constant _TELLOR_GETTERS = 0xabd9bea65759494fe86471c8386762f989e1f2e778949e94efa4a9d1c4b3545a; //keccak256("_TELLOR_GETTERS"); bytes32 constant _TIME_OF_LAST_NEW_VALUE = 0x2c8b528fbaf48aaf13162a5a0519a7ad5a612da8ff8783465c17e076660a59f1; //keccak256("_TIME_OF_LAST_NEW_VALUE"); bytes32 constant _TIME_TARGET = 0xd4f87b8d0f3d3b7e665df74631f6100b2695daa0e30e40eeac02172e15a999e1; //keccak256("_TIME_TARGET"); bytes32 constant _TIMESTAMP = 0x2f9328a9c75282bec25bb04befad06926366736e0030c985108445fa728335e5; //keccak256("_TIMESTAMP"); bytes32 constant _TOTAL_SUPPLY = 0xe6148e7230ca038d456350e69a91b66968b222bfac9ebfbea6ff0a1fb7380160; //keccak256("_TOTAL_SUPPLY"); bytes32 constant _TOTAL_TIP = 0x1590276b7f31dd8e2a06f9a92867333eeb3eddbc91e73b9833e3e55d8e34f77d; //keccak256("_TOTAL_TIP"); bytes32 constant _VALUE = 0x9147231ab14efb72c38117f68521ddef8de64f092c18c69dbfb602ffc4de7f47; //keccak256("_VALUE"); bytes32 constant _EIP_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; }
Getter function for the top 5 requests with highest payouts. This function is used within the getNewVariablesOnDeck function/
function getTopRequestIDs() public view returns (uint256[5] memory _requestIds) { uint256[5] memory _max; uint256[5] memory _index; (_max, _index) = _getMax5(requestQ); for (uint256 i = 0; i < 5; i++) { if (_max[i] != 0) { _requestIds[i] = requestIdByRequestQIndex[_index[i]]; _requestIds[i] = currentMiners[4 - i].value; } } }
9,847,282
./partial_match/1/0xbc446fA602Ece8A4fD163cD356B598ef1C8aaE4E/sources/src/settled-cash/CrossMarginCashMath.sol
get numeraire and underlying needed to fully collateralize calculates left side and right side of the payout profile _detail margin details scenarios of all the options payouts are the payouts at a given scenario return numeraireNeeded with {numeraire asset's} decimals return underlyingNeeded with {underlying asset's} decimals/ if put options exist, get amount of numeraire needed (left side of payout profile) if call options exist, get amount of underlying needed (right side of payout profile) crediting the numeraire if underlying has a positive payout
function _getCollateralNeeds(CrossMarginDetail memory _detail, uint256[] memory scenarios, int256[] memory payouts) internal pure returns (uint256 numeraireNeeded, uint256 underlyingNeeded) { bool hasPuts = _detail.putStrikes.length > 0; bool hasCalls = _detail.callStrikes.length > 0; (int256 minPayout, uint256 minPayoutIndex) = payouts.minWithIndex(); if (hasPuts) numeraireNeeded = _getNumeraireNeeded(minPayout, _detail.putStrikes, _detail.putWeights); if (hasCalls) underlyingNeeded = _getUnderlyingNeeded(_detail.callWeights); numeraireNeeded = _getUnderlyingAdjustedNumeraireNeeded(scenarios, minPayout, minPayoutIndex, numeraireNeeded, underlyingNeeded); }
4,192,577
./full_match/80001/0xca2293d1117555366114Bc2b20FD33C8a1920459/sources/contracts/CrowdFunding.sol
Creating an array of campaigns
function listCampaigns() public view returns (Campaign[] memory) { Campaign[] memory campaignList = new Campaign[](numberOfCampaigns); for(uint i = 0; i < numberOfCampaigns; i++) { Campaign storage item = campaigns[i]; campaignList[i] = item; } return campaignList; }
5,662,505
/*pragma solidity ^0.5.0; import {HighCardGameState} from './HighCardGameState.sol'; import {IERC20} from '../token/IERC20.sol'; import {SafeMath} from '../math/SafeMath.sol'; contract HeadsUpTables { using SafeMath for uint256; // For Domain Separator bytes32 constant SALT = 0xf1ae92db93da5bd8411028f6531126984a6eb2e7f66b19e5c22d5a7b0fb00bc7; // Domain separator completed on contract construction bytes32 public DOMAIN_SEPARATOR; // Dispute types uint8 constant public noDispute = 0; uint8 constant public unresponsiveDispute = 1; uint8 constant public malformedDispute = 2; // Action types uint8 constant public foldAction = 0; uint8 constant public callAction = 1; uint8 constant public raiseAction = 2; uint8 constant public revealAction = 3; uint8 constant public commitAction = 4; // Structs struct State { uint256[2] currentBalances; bytes encodedState; } struct Claim { uint8 disputeType; bytes disputeData; address proposer; uint256 redeemTime; } struct Table { bytes32 tableID; // Deterministic ID for any 2 players (same 2 addresses can only play one table at a time) bytes32 sessionID; // Uniqueness in case same addresses play multiple times address[2] participants; uint256 buyIn; uint256 smallBlind; uint256 tableExpiration; uint256 joinExpiration; State state; Claim claim; bool inClaim; bool isJoined; uint256 disputeDuration; } HighCardGameState poker; mapping (bytes32 => Table) tables; mapping (bytes32 => bool) public activeTable; bytes32[] public activeTables; IERC20 public token; /// PUBLIC STATE MODIFYING FUNCTIONS constructor (address _pokerGameAddress, address _tokenAddress) public { DOMAIN_SEPARATOR = keccak256(abi.encode(address(this), SALT)); poker = HighCardGameState(_pokerGameAddress); token = IERC20(_tokenAddress); } function openTable(address[2] memory participants, bytes memory openData, uint8[2] memory vs, bytes32[2] memory rs, bytes32[2] memory ss, bytes32 uniqueSessionID) public { require(participants[0] == msg.sender || participants[1] == msg.sender); bytes32 tableID = getTableID(participants[0], participants[1]); bytes32 hash = getTableTransactionHash(tableID, uniqueSessionID, openData); require(ecrecover(hash, vs[0], rs[0], ss[0]) == participants[0]); require(ecrecover(hash, vs[1], rs[1], ss[1]) == participants[1]); require(tables[tableID].tableID != tableID); require(!activeTable[tableID]); (uint256 buyIn, uint256 tableDuration, uint256 joinDuration, uint256 disputeDuration) = abi.decode(openData, (uint256, uint256, uint256, uint256)); // Optional (but recommended): require duration minimums //require(tableDuration >= 600 && disputeDuration >= 600) require(buyIn%100==0); require(token.transferFrom(msg.sender, address(this), buyIn)); require(joinDuration<tableDuration); tables[tableID].tableExpiration = tableDuration.add(now); tables[tableID].joinExpiration = joinDuration.add(now); tables[tableID].disputeDuration = disputeDuration; tables[tableID].tableID = tableID; tables[tableID].sessionID = uniqueSessionID; tables[tableID].participants[0] = participants[0]; tables[tableID].participants[1] = participants[1]; tables[tableID].buyIn = buyIn; tables[tableID].smallBlind = buyIn.div(100); require(tables[tableID].smallBlind>0); if (participants[0] == msg.sender) { tables[tableID].state.currentBalances[0] = buyIn; } else { tables[tableID].state.currentBalances[1] = buyIn; } activeTable[tableID] = true; activeTables.push(tableID); } function joinTable(address[2] memory participants) public { bytes32 tableID = getTableID(participants[0], participants[1]); require(activeTable[tableID]); require(tables[tableID].tableID == tableID); require(!tables[tableID].isJoined); require(now < tables[tableID].joinExpiration); require(token.transferFrom(msg.sender, address(this), tables[tableID].buyIn)); require(tables[tableID].participants[0] == msg.sender || tables[tableID].participants[1] == msg.sender); if (tables[tableID].participants[0] == msg.sender) { require(tables[tableID].state.currentBalances[0] == 0); tables[tableID].state.currentBalances[0] = tables[tableID].buyIn; } else { require(tables[tableID].state.currentBalances[1] == 0); tables[tableID].state.currentBalances[1] = tables[tableID].buyIn; } tables[tableID].state.encodedState = poker.initialEncodedState(tables[tableID].smallBlind); tables[tableID].isJoined = true; } function proposeClaim(bytes32 tableID, bytes memory ClaimData, uint8 v, bytes32 r, bytes32 s) public { require(activeTable[tableID]); require(tables[tableID].isJoined); if (!tables[tableID].inClaim) { // Must propose a Claim before table expires if no settlment already exists. require(now < tables[tableID].tableExpiration); } else { // If Claim already exists can propose a challenge up until the end of existing Claim dispute period. require(now < tables[tableID].claim.redeemTime); } // Verify and unpack Claim data (bytes memory finalStateData, address proposer, uint8 disputeType, bytes memory disputeData) = verifyUnpackClaimData(tableID, ClaimData, v, r, s); // Verify and unpack final state data bytes memory encodedNewState = verifySignedStateData(tableID, finalStateData); // Handle Claim handleClaim(tableID, encodedNewState, proposer, disputeType, disputeData); } function claimExpiredTable(bytes32 tableID) public { require(activeTable[tableID]); require(!tables[tableID].inClaim); if (tables[tableID].isJoined) { if (now > tables[tableID].tableExpiration) { closeTable(tableID); } } else { if (now > tables[tableID].joinExpiration) { closeTable(tableID); } } } function claimExpiredClaim(bytes32 tableID) public { require(activeTable[tableID]); require(tables[tableID].inClaim); require(now > tables[tableID].claim.redeemTime); require(tables[tableID].claim.proposer == tables[tableID].participants[0] || tables[tableID].claim.proposer == tables[tableID].participants[1]); if (tables[tableID].claim.proposer == tables[tableID].participants[0]) { tables[tableID].state.currentBalances[0] = tables[tableID].state.currentBalances[0].add(poker.getPot(tables[tableID].state.encodedState)); } else { tables[tableID].state.currentBalances[1] = tables[tableID].state.currentBalances[1].add(poker.getPot(tables[tableID].state.encodedState)); } closeTable(tableID); } /// INTERNAL (PROTECTED) STATE MODIFYING FUNCTIONS function advanceToVerifiedState(bytes32 tableID, bytes memory encodedState) internal { tables[tableID].state.encodedState = encodedState; tables[tableID].state.currentBalances = poker.getBalances(encodedState); } function handleClaim(bytes32 tableID, bytes memory encodedNewState, address proposer, uint8 disputeType, bytes memory disputeData) internal { require(poker.isValidStateFastForward(tables[tableID].state.encodedState, encodedNewState, tables[tableID].participants, tables[tableID].smallBlind)); advanceToVerifiedState(tableID, encodedNewState); if (disputeType==noDispute && poker.getActionType(tables[tableID].state.encodedState)!=commitAction) { require(false); } else if (disputeType==noDispute && poker.getActionType(tables[tableID].state.encodedState)==commitAction && (tables[tableID].state.currentBalances[0]==0 || tables[tableID].state.currentBalances[1]==0)) { closeTable(tableID); } else if (disputeType==noDispute || (disputeType == unresponsiveDispute && verifyUnresponsiveDispute(tableID, disputeData, proposer))) { tables[tableID].inClaim = true; uint256 redeemTime = tables[tableID].disputeDuration.add(now); tables[tableID].claim = Claim({proposer: proposer, disputeType: disputeType, disputeData: disputeData, redeemTime: redeemTime}); } else if (disputeType==malformedDispute && verifyMalformedDispute(tableID, disputeData, proposer)) { if (proposer == tables[tableID].participants[0]) { tables[tableID].state.currentBalances[0] = tables[tableID].state.currentBalances[0].add(poker.getPot(tables[tableID].state.encodedState)); } else if (proposer == tables[tableID].participants[1]) { tables[tableID].state.currentBalances[1] = tables[tableID].state.currentBalances[1].add(poker.getPot(tables[tableID].state.encodedState)); } else { require(false); } closeTable(tableID); } else { require(false); } } function closeTable(bytes32 tableID) internal { uint256 amount1 = tables[tableID].state.currentBalances[0]; uint256 amount2 = tables[tableID].state.currentBalances[1]; address p1 = tables[tableID].participants[0]; address p2 = tables[tableID].participants[1]; if (tables[tableID].isJoined) { require(amount1.add(amount2) == tables[tableID].buyIn.mul(2)); } else { require(amount1.add(amount2) == tables[tableID].buyIn); } delete tables[tableID]; delete activeTable[tableID]; for (uint256 i=0; i<activeTables.length; i++) { if (activeTables[i] == tableID) { activeTables[i] = activeTables[activeTables.length-1]; delete activeTables[activeTables.length-1]; activeTables.length--; } } require(token.transfer(p1, amount1)); require(token.transfer(p2, amount2)); } /// PUBLIC VIEW/PURE FUNCTIONS function getTableID(address participant1, address participant2) public view returns (bytes32) { require(participant1<participant2); return keccak256(abi.encodePacked(DOMAIN_SEPARATOR, participant1, participant2)); } function getTableTransactionHash(bytes32 tableID, bytes32 sessionID, bytes memory txData) public pure returns (bytes32) { return prefixedHash(tableID, sessionID, keccak256(txData)); } function getTableOverview(bytes32 tableID) public view returns (address[2] memory, uint256[4] memory, bool[2] memory) { require(activeTable[tableID]); uint256[4] memory nums; nums[0] = tables[tableID].buyIn; nums[1] = tables[tableID].tableExpiration; nums[2] = tables[tableID].joinExpiration; nums[3] = tables[tableID].disputeDuration; bool[2] memory bools; bools[0] = tables[tableID].isJoined; bools[1] = tables[tableID].inClaim; return (tables[tableID].participants, nums, bools); } function getTableClaim(bytes32 tableID) public view returns (uint8, address, uint256, bytes memory) { require(activeTable[tableID]); require(tables[tableID].inClaim); return (tables[tableID].claim.disputeType, tables[tableID].claim.proposer, tables[tableID].claim.redeemTime, tables[tableID].claim.disputeData); } function getTableState(bytes32 tableID) public view returns (bytes memory) { require(activeTable[tableID]); return tables[tableID].state.encodedState; } function verifySignedStateData(bytes32 tableID, bytes memory stateData) public view returns (bytes memory) { (bytes memory encodedState, uint8[2] memory vs, bytes32[2] memory rs, bytes32[2] memory ss) = abi.decode(stateData, (bytes, uint8[2], bytes32[2], bytes32[2])); bytes32 hash = getOpenTableTransactionHash(tableID, encodedState); require(ecrecover(hash, vs[0], rs[0], ss[0]) == tables[tableID].participants[0]); require(ecrecover(hash, vs[1], rs[1], ss[1]) == tables[tableID].participants[1]); return encodedState; } function verifyHalfSignedStateData(bytes32 tableID, bytes memory stateData, address signer) public view returns (bytes memory) { (bytes memory encodedState, uint8 v, bytes32 r, bytes32 s) = abi.decode(stateData, (bytes, uint8, bytes32, bytes32)); bytes32 hash = getOpenTableTransactionHash(tableID, encodedState); require(ecrecover(hash, v, r, s) == signer); return encodedState; } function verifyUnpackClaimData(bytes32 tableID, bytes memory ClaimData, uint8 v, bytes32 r, bytes32 s) public view returns (bytes memory, address, uint8, bytes memory) { (bytes memory finalStateData, address proposer, uint8 disputeType, bytes memory disputeData) = abi.decode(ClaimData, (bytes, address, uint8, bytes)); require(proposer==tables[tableID].participants[0] || proposer==tables[tableID].participants[1]); bytes32 hash = getOpenTableTransactionHash(tableID, ClaimData); require(ecrecover(hash, v, r, s)==proposer); return (finalStateData, proposer, disputeType, disputeData); } function verifyUnresponsiveDispute(bytes32 tableID, bytes memory disputeData, address proposer) public view returns (bool) { bytes memory encodedNewState = verifyHalfSignedStateData(tableID, disputeData, proposer); return poker.isValidStateTransition(tables[tableID].state.encodedState, encodedNewState, tables[tableID].participants, tables[tableID].smallBlind); } function verifyMalformedDispute(bytes32 tableID, bytes memory disputeData, address proposer) public view returns (bool) { address signer = tables[tableID].participants[0]; if (proposer == tables[tableID].participants[0]) { signer = tables[tableID].participants[1]; } bytes memory encodedNewState = verifyHalfSignedStateData(tableID, disputeData, signer); return !poker.isValidStateTransition(tables[tableID].state.encodedState, encodedNewState, tables[tableID].participants, tables[tableID].smallBlind); } /// INTERNAL VIEW/PURE FUNCTIONS function getOpenTableTransactionHash(bytes32 tableID, bytes memory txData) internal view returns (bytes32) { return prefixedHash(tableID, tables[tableID].sessionID, keccak256(txData)); } function prefixedHash(bytes32 tableID, bytes32 sessionID, bytes32 txHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", tableID, sessionID, txHash)); } }*/
Must propose a Claim before table expires if no settlment already exists. If Claim already exists can propose a challenge up until the end of existing Claim dispute period.
function proposeClaim(bytes32 tableID, bytes memory ClaimData, uint8 v, bytes32 r, bytes32 s) public { require(activeTable[tableID]); require(tables[tableID].isJoined); if (!tables[tableID].inClaim) { require(now < tables[tableID].tableExpiration); require(now < tables[tableID].claim.redeemTime); } }
7,281,836
pragma solidity ^0.5.0; import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./SafeMathUInt128.sol"; import "./SafeCast.sol"; import "./Utils.sol"; import "./Storage.sol"; import "./Config.sol"; import "./Events.sol"; import "./Bytes.sol"; import "./Operations.sol"; import "./UpgradeableMaster.sol"; import "./uniswap/UniswapV2Factory.sol"; import "./PairTokenManager.sol"; /// @title zkSync main contract /// @author Matter Labs /// @author ZKSwap L2 Labs contract ZkSync is PairTokenManager, UpgradeableMaster, Storage, Config, Events, ReentrancyGuard { using SafeMath for uint256; using SafeMathUInt128 for uint128; bytes32 public constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //create pair function createPair(address _tokenA, address _tokenB) external { requireActive(); governance.requireTokenLister(msg.sender); //check _tokenA is registered or not uint16 tokenAID = governance.validateTokenAddress(_tokenA); //check _tokenB is registered or not uint16 tokenBID = governance.validateTokenAddress(_tokenB); //make sure _tokenA is fee token require(tokenAID <= MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS, "tokenA should be fee token"); //create pair address pair = pairmanager.createPair(_tokenA, _tokenB); require(pair != address(0), "pair is invalid"); addPairToken(pair); registerCreatePair( tokenAID, _tokenA, tokenBID, _tokenB, validatePairTokenAddress(pair), pair ); } //create pair including ETH function createETHPair(address _tokenERC20) external { requireActive(); governance.requireTokenLister(msg.sender); //check _tokenERC20 is registered or not uint16 erc20ID = governance.validateTokenAddress(_tokenERC20); //create pair address pair = pairmanager.createPair(address(0), _tokenERC20); require(pair != address(0), "pair is invalid"); addPairToken(pair); registerCreatePair( 0, address(0), erc20ID, _tokenERC20, validatePairTokenAddress(pair), pair ); } function registerCreatePair(uint16 _tokenAID, address _tokenA, uint16 _tokenBID, address _tokenB, uint16 _tokenPair, address _pair) internal { // Priority Queue request Operations.CreatePair memory op = Operations.CreatePair({ accountId : 0, //unknown at this point tokenA : _tokenAID, tokenB : _tokenBID, tokenPair : _tokenPair, pair : _pair }); bytes memory pubData = Operations.writeCreatePairPubdata(op); bytes memory userData = abi.encodePacked( _tokenA, // tokenA address _tokenB // tokenB address ); addPriorityRequest(Operations.OpType.CreatePair, pubData, userData); emit OnchainCreatePair(_tokenAID, _tokenBID, _tokenPair, _pair); } // Upgrade functional /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external returns (uint) { return UPGRADE_NOTICE_PERIOD; } /// @notice Notification that upgrade notice period started function upgradeNoticePeriodStarted() external { } /// @notice Notification that upgrade preparation status is activated function upgradePreparationStarted() external { upgradePreparationActive = true; upgradePreparationActivationTime = now; } /// @notice Notification that upgrade canceled function upgradeCanceled() external { upgradePreparationActive = false; upgradePreparationActivationTime = 0; } /// @notice Notification that upgrade finishes function upgradeFinishes() external { upgradePreparationActive = false; upgradePreparationActivationTime = 0; } /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external returns (bool) { return !exodusMode; } constructor() public { governance = Governance(msg.sender); zkSyncCommitBlockAddress = address(this); zkSyncExitAddress = address(this); } /// @notice Franklin contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// _governanceAddress The address of Governance contract /// _verifierAddress The address of Verifier contract /// _ // FIXME: remove _genesisAccAddress /// _genesisRoot Genesis blocks (first block) root function initialize(bytes calldata initializationParameters) external { require(address(governance) == address(0), "init0"); initializeReentrancyGuard(); ( address _governanceAddress, address _verifierAddress, address _verifierExitAddress, address _pairManagerAddress ) = abi.decode(initializationParameters, (address, address, address, address)); verifier = Verifier(_verifierAddress); verifierExit = VerifierExit(_verifierExitAddress); governance = Governance(_governanceAddress); pairmanager = UniswapV2Factory(_pairManagerAddress); maxDepositAmount = DEFAULT_MAX_DEPOSIT_AMOUNT; withdrawGasLimit = ERC20_WITHDRAWAL_GAS_LIMIT; } function setGenesisRootAndAddresses(bytes32 _genesisRoot, address _zkSyncCommitBlockAddress, address _zkSyncExitAddress) external { // This function cannot be called twice as long as // _zkSyncCommitBlockAddress and _zkSyncExitAddress have been set to // non-zero. require(zkSyncCommitBlockAddress == address(0), "sraa1"); require(zkSyncExitAddress == address(0), "sraa2"); blocks[0].stateRoot = _genesisRoot; zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress; zkSyncExitAddress = _zkSyncExitAddress; } /// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} /// @notice Sends tokens /// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount /// @param _token Token address /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @param _maxAmount Maximum possible amount of tokens to transfer to this account function withdrawERC20Guarded(IERC20 _token, address _to, uint128 _amount, uint128 _maxAmount) external returns (uint128 withdrawnAmount) { require(msg.sender == address(this), "wtg10"); // wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed) uint16 lpTokenId = tokenIds[address(_token)]; uint256 balance_before = _token.balanceOf(address(this)); if (lpTokenId > 0) { validatePairTokenAddress(address(_token)); pairmanager.mint(address(_token), _to, _amount); } else { require(Utils.sendERC20(_token, _to, _amount), "wtg11"); // wtg11 - ERC20 transfer fails } uint256 balance_after = _token.balanceOf(address(this)); uint256 balance_diff = balance_before.sub(balance_after); require(balance_diff <= _maxAmount, "wtg12"); // wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount return SafeCast.toUint128(balance_diff); } /// @notice executes pending withdrawals /// @param _n The number of withdrawals to complete starting from oldest function completeWithdrawals(uint32 _n) external nonReentrant { // TODO: when switched to multi validators model we need to add incentive mechanism to call complete. uint32 toProcess = Utils.minU32(_n, numberOfPendingWithdrawals); uint32 startIndex = firstPendingWithdrawalIndex; numberOfPendingWithdrawals -= toProcess; firstPendingWithdrawalIndex += toProcess; for (uint32 i = startIndex; i < startIndex + toProcess; ++i) { uint16 tokenId = pendingWithdrawals[i].tokenId; address to = pendingWithdrawals[i].to; // send fails are ignored hence there is always a direct way to withdraw. delete pendingWithdrawals[i]; bytes22 packedBalanceKey = packAddressAndTokenId(to, tokenId); uint128 amount = balancesToWithdraw[packedBalanceKey].balanceToWithdraw; // amount is zero means funds has been withdrawn with withdrawETH or withdrawERC20 if (amount != 0) { balancesToWithdraw[packedBalanceKey].balanceToWithdraw -= amount; bool sent = false; if (tokenId == 0) { address payable toPayable = address(uint160(to)); sent = Utils.sendETHNoRevert(toPayable, amount); } else { address tokenAddr = address(0); if (tokenId < PAIR_TOKEN_START_ID) { // It is normal ERC20 tokenAddr = governance.tokenAddresses(tokenId); } else { // It is pair token tokenAddr = tokenAddresses[tokenId]; } // tokenAddr cannot be 0 require(tokenAddr != address(0), "cwt0"); // we can just check that call not reverts because it wants to withdraw all amount (sent,) = address(this).call.gas(withdrawGasLimit)( abi.encodeWithSignature("withdrawERC20Guarded(address,address,uint128,uint128)", tokenAddr, to, amount, amount) ); } if (!sent) { balancesToWithdraw[packedBalanceKey].balanceToWithdraw += amount; } } } if (toProcess > 0) { emit PendingWithdrawalsComplete(startIndex, startIndex + toProcess); } } /// @notice Accrues users balances from deposit priority requests in Exodus mode /// @dev WARNING: Only for Exodus mode /// @dev Canceling may take several separate transactions to be completed /// @param _n number of requests to process function cancelOutstandingDepositsForExodusMode(uint64 _n) external nonReentrant { require(exodusMode, "coe01"); // exodus mode not active uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n); require(toProcess > 0, "coe02"); // no deposits to process for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) { if (priorityRequests[id].opType == Operations.OpType.Deposit) { Operations.Deposit memory op = Operations.readDepositPubdata(priorityRequests[id].pubData); bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId); balancesToWithdraw[packedBalanceKey].balanceToWithdraw += op.amount; } delete priorityRequests[id]; } firstPriorityRequestId += toProcess; totalOpenPriorityRequests -= toProcess; } /// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit /// @param _franklinAddr The receiver Layer 2 address function depositETH(address _franklinAddr) external payable nonReentrant { requireActive(); registerDeposit(0, SafeCast.toUint128(msg.value), _franklinAddr); } /// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to sender /// @param _amount Ether amount to withdraw function withdrawETH(uint128 _amount) external nonReentrant { registerWithdrawal(0, _amount, msg.sender); (bool success,) = msg.sender.call.value(_amount)(""); require(success, "fwe11"); // ETH withdraw failed } /// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to _to address /// @param _amount Ether amount to withdraw function withdrawETHWithAddress(uint128 _amount, address payable _to) external nonReentrant { require(_to != address(0), "ipa11"); registerWithdrawal(0, _amount, _to); (bool success,) = _to.call.value(_amount)(""); require(success, "fwe12"); // ETH withdraw failed } /// @notice Config amount limit for each ERC20 deposit /// @param _amount Max deposit amount function setMaxDepositAmount(uint128 _amount) external { governance.requireGovernor(msg.sender); maxDepositAmount = _amount; } /// @notice Config gas limit for withdraw erc20 token /// @param _gasLimit withdraw erc20 gas limit function setWithDrawGasLimit(uint256 _gasLimit) external { governance.requireGovernor(msg.sender); withdrawGasLimit = _gasLimit; } /// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit /// @param _token Token address /// @param _amount Token amount /// @param _franklinAddr Receiver Layer 2 address function depositERC20(IERC20 _token, uint104 _amount, address _franklinAddr) external nonReentrant { requireActive(); // Get token id by its address uint16 lpTokenId = tokenIds[address(_token)]; uint16 tokenId = 0; if (lpTokenId == 0) { // This means it is not a pair address tokenId = governance.validateTokenAddress(address(_token)); } else { lpTokenId = validatePairTokenAddress(address(_token)); } uint256 balance_before = 0; uint256 balance_after = 0; uint128 deposit_amount = 0; if (lpTokenId > 0) { // Note: For lp token, main contract always has no money balance_before = _token.balanceOf(msg.sender); pairmanager.burn(address(_token), msg.sender, SafeCast.toUint128(_amount)); balance_after = _token.balanceOf(msg.sender); deposit_amount = SafeCast.toUint128(balance_before.sub(balance_after)); require(deposit_amount <= maxDepositAmount, "fd011"); registerDeposit(lpTokenId, deposit_amount, _franklinAddr); } else { balance_before = _token.balanceOf(address(this)); require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012"); // token transfer failed deposit balance_after = _token.balanceOf(address(this)); deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before)); require(deposit_amount <= maxDepositAmount, "fd013"); registerDeposit(tokenId, deposit_amount, _franklinAddr); } } /// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to sender /// @param _token Token address /// @param _amount amount to withdraw function withdrawERC20(IERC20 _token, uint128 _amount) external nonReentrant { uint16 lpTokenId = tokenIds[address(_token)]; uint16 tokenId = 0; if (lpTokenId == 0) { // This means it is not a pair address tokenId = governance.validateTokenAddress(address(_token)); } else { tokenId = validatePairTokenAddress(address(_token)); } bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId); uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw; uint128 withdrawnAmount = this.withdrawERC20Guarded(_token, msg.sender, _amount, balance); registerWithdrawal(tokenId, withdrawnAmount, msg.sender); } /// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to _to address /// @param _token Token address /// @param _amount amount to withdraw /// @param _to address to withdraw function withdrawERC20WithAddress(IERC20 _token, uint128 _amount, address payable _to) external nonReentrant { require(_to != address(0), "ipa12"); uint16 lpTokenId = tokenIds[address(_token)]; uint16 tokenId = 0; if (lpTokenId == 0) { // This means it is not a pair address tokenId = governance.validateTokenAddress(address(_token)); } else { tokenId = validatePairTokenAddress(address(_token)); } bytes22 packedBalanceKey = packAddressAndTokenId(_to, tokenId); uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw; uint128 withdrawnAmount = this.withdrawERC20Guarded(_token, _to, _amount, balance); registerWithdrawal(tokenId, withdrawnAmount, _to); } /// @notice Register full exit request - pack pubdata, add priority request /// @param _accountId Numerical id of the account /// @param _token Token address, 0 address for ether function fullExit(uint32 _accountId, address _token) external nonReentrant { requireActive(); require(_accountId <= MAX_ACCOUNT_ID, "fee11"); uint16 tokenId; if (_token == address(0)) { tokenId = 0; } else { tokenId = governance.validateTokenAddress(_token); require(tokenId <= MAX_AMOUNT_OF_REGISTERED_TOKENS, "fee12"); } // Priority Queue request Operations.FullExit memory op = Operations.FullExit({ accountId : _accountId, owner : msg.sender, tokenId : tokenId, amount : 0 // unknown at this point }); bytes memory pubData = Operations.writeFullExitPubdata(op); addPriorityRequest(Operations.OpType.FullExit, pubData, ""); // User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value // In this case operator should just overwrite this slot during confirming withdrawal bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId); balancesToWithdraw[packedBalanceKey].gasReserveValue = 0xff; } /// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event /// @param _tokenId Token by id /// @param _amount Token amount /// @param _owner Receiver function registerDeposit( uint16 _tokenId, uint128 _amount, address _owner ) internal { // Priority Queue request Operations.Deposit memory op = Operations.Deposit({ accountId : 0, // unknown at this point owner : _owner, tokenId : _tokenId, amount : _amount }); bytes memory pubData = Operations.writeDepositPubdata(op); addPriorityRequest(Operations.OpType.Deposit, pubData, ""); emit OnchainDeposit( msg.sender, _tokenId, _amount, _owner ); } /// @notice Register withdrawal - update user balance and emit OnchainWithdrawal event /// @param _token - token by id /// @param _amount - token amount /// @param _to - address to withdraw to function registerWithdrawal(uint16 _token, uint128 _amount, address payable _to) internal { bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token); uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw; balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.sub(_amount); emit OnchainWithdrawal( _to, _token, _amount ); } /// @notice Checks that current state not is exodus mode function requireActive() internal view { require(!exodusMode, "fre11"); // exodus mode activated } // Priority queue /// @notice Saves priority request in storage /// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event /// @param _opType Rollup operation type /// @param _pubData Operation pubdata function addPriorityRequest( Operations.OpType _opType, bytes memory _pubData, bytes memory _userData ) internal { // Expiration block is: current block number + priority expiration delta uint256 expirationBlock = block.number + PRIORITY_EXPIRATION; uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests; priorityRequests[nextPriorityRequestId] = PriorityOperation({ opType : _opType, pubData : _pubData, expirationBlock : expirationBlock }); emit NewPriorityRequest( msg.sender, nextPriorityRequestId, _opType, _pubData, _userData, expirationBlock ); totalOpenPriorityRequests++; } // The contract is too large. Break some functions to zkSyncCommitBlockAddress function() external payable { address nextAddress = zkSyncCommitBlockAddress; require(nextAddress != address(0), "zkSyncCommitBlockAddress should be set"); // Execute external function from facet using delegatecall and return any value. assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), nextAddress, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } } pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { /// Address of lock flag variable. /// Flag is placed at random memory location to not interfere with Storage contract. uint constant private LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1; function initializeReentrancyGuard () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. assembly { sstore(LOCK_FLAG_ADDRESS, 1) } } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { bool notEntered; assembly { notEntered := sload(LOCK_FLAG_ADDRESS) } // On the first call to nonReentrant, _notEntered will be true require(notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail assembly { sstore(LOCK_FLAG_ADDRESS, 0) } _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) assembly { sstore(LOCK_FLAG_ADDRESS, 1) } } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.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 SafeMathUInt128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 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} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. * * _Available since v2.5.0._ */ 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); } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "./Bytes.sol"; library Utils { /// @notice Returns lesser of two values function minU32(uint32 a, uint32 b) internal pure returns (uint32) { return a < b ? a : b; } /// @notice Returns lesser of two values function minU64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } /// @notice Sends tokens /// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard /// @dev NOTE: call `transfer` to this token may return (bool) or nothing /// @param _token Token address /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function sendERC20(IERC20 _token, address _to, uint256 _amount) internal returns (bool) { (bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call( abi.encodeWithSignature("transfer(address,uint256)", _to, _amount) ); // `transfer` method may return (bool) or nothing. bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool)); return callSuccess && returnedSuccess; } /// @notice Transfers token from one address to another /// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard /// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing /// @param _token Token address /// @param _from Address of sender /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function transferFromERC20(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { (bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call( abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount) ); // `transferFrom` method may return (bool) or nothing. bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool)); return callSuccess && returnedSuccess; } /// @notice Sends ETH /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function sendETHNoRevert(address payable _to, uint256 _amount) internal returns (bool) { // TODO: Use constant from Config uint256 ETH_WITHDRAWAL_GAS_LIMIT = 10000; (bool callSuccess, ) = _to.call.gas(ETH_WITHDRAWAL_GAS_LIMIT).value(_amount)(""); return callSuccess; } /// @notice Recovers signer's address from ethereum signature for given message /// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1) /// @param _message signed message. /// @return address of the signer function recoverAddressFromEthSignature(bytes memory _signature, bytes memory _message) internal pure returns (address) { require(_signature.length == 65, "ves10"); // incorrect signature length bytes32 signR; bytes32 signS; uint offset = 0; (offset, signR) = Bytes.readBytes32(_signature, offset); (offset, signS) = Bytes.readBytes32(_signature, offset); uint8 signV = uint8(_signature[offset]); return ecrecover(keccak256(_message), signV, signR, signS); } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "./Governance.sol"; import "./Verifier.sol"; import "./VerifierExit.sol"; import "./Operations.sol"; import "./uniswap/UniswapV2Factory.sol"; /// @title ZKSwap storage contract /// @author Matter Labs /// @author ZKSwap L2 Labs contract Storage { /// @notice Flag indicates that upgrade preparation status is active /// @dev Will store false in case of not active upgrade mode bool public upgradePreparationActive; /// @notice Upgrade preparation activation timestamp (as seconds since unix epoch) /// @dev Will be equal to zero in case of not active upgrade mode uint public upgradePreparationActivationTime; /// @notice Verifier contract. Used to verify block proof and exit proof Verifier internal verifier; VerifierExit internal verifierExit; /// @notice Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list Governance internal governance; UniswapV2Factory internal pairmanager; struct BalanceToWithdraw { uint128 balanceToWithdraw; uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value } /// @notice Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw mapping(bytes22 => BalanceToWithdraw) public balancesToWithdraw; /// @notice verified withdrawal pending to be executed. struct PendingWithdrawal { address to; uint16 tokenId; } /// @notice Verified but not executed withdrawals for addresses stored in here (key is pendingWithdrawal's index in pending withdrawals queue) mapping(uint32 => PendingWithdrawal) public pendingWithdrawals; uint32 public firstPendingWithdrawalIndex; uint32 public numberOfPendingWithdrawals; /// @notice Total number of verified blocks i.e. blocks[totalBlocksVerified] points at the latest verified block (block 0 is genesis) uint32 public totalBlocksVerified; /// @notice Total number of checked blocks uint32 public totalBlocksChecked; /// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block uint32 public totalBlocksCommitted; /// @notice Rollup block data (once per block) /// @member validator Block producer /// @member committedAtBlock ETH block number at which this block was committed /// @member cumulativeOnchainOperations Total number of operations in this and all previous blocks /// @member priorityOperations Total number of priority operations for this block /// @member commitment Hash of the block circuit commitment /// @member stateRoot New tree root hash /// /// Consider memory alignment when changing field order: https://solidity.readthedocs.io/en/v0.4.21/miscellaneous.html struct Block { uint32 committedAtBlock; uint64 priorityOperations; uint32 chunks; bytes32 withdrawalsDataHash; /// can be restricted to 16 bytes to reduce number of required storage slots bytes32 commitment; bytes32 stateRoot; } /// @notice Blocks by Franklin block id mapping(uint32 => Block) public blocks; /// @notice Onchain operations - operations processed inside rollup blocks /// @member opType Onchain operation type /// @member amount Amount used in the operation /// @member pubData Operation pubdata struct OnchainOperation { Operations.OpType opType; bytes pubData; } /// @notice Flag indicates that a user has exited certain token balance (per account id and tokenId) mapping(uint32 => mapping(uint16 => bool)) public exited; mapping(uint32 => mapping(uint32 => bool)) public swap_exited; /// @notice Flag indicates that exodus (mass exit) mode is triggered /// @notice Once it was raised, it can not be cleared again, and all users must exit bool public exodusMode; /// @notice User authenticated fact hashes for some nonce. mapping(address => mapping(uint32 => bytes32)) public authFacts; /// @notice Priority Operation container /// @member opType Priority operation type /// @member pubData Priority operation public data /// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before) struct PriorityOperation { Operations.OpType opType; bytes pubData; uint256 expirationBlock; } /// @notice Priority Requests mapping (request id - operation) /// @dev Contains op type, pubdata and expiration block of unsatisfied requests. /// @dev Numbers are in order of requests receiving mapping(uint64 => PriorityOperation) public priorityRequests; /// @notice First open priority request id uint64 public firstPriorityRequestId; /// @notice Total number of requests uint64 public totalOpenPriorityRequests; /// @notice Total number of committed requests. /// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big uint64 public totalCommittedPriorityRequests; /// @notice Packs address and token id into single word to use as a key in balances mapping function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) { return bytes22((uint176(_address) | (uint176(_tokenId) << 160))); } /// @notice Gets value from balancesToWithdraw function getBalanceToWithdraw(address _address, uint16 _tokenId) public view returns (uint128) { return balancesToWithdraw[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw; } address public zkSyncCommitBlockAddress; address public zkSyncExitAddress; /// @notice Limit the max amount for each ERC20 deposit uint128 public maxDepositAmount; /// @notice withdraw erc20 token gas limit uint256 public withdrawGasLimit; } pragma solidity ^0.5.0; /// @title ZKSwap configuration constants /// @author Matter Labs /// @author ZKSwap L2 Labs contract Config { /// @notice ERC20 token withdrawal gas limit, used only for complete withdrawals uint256 constant ERC20_WITHDRAWAL_GAS_LIMIT = 350000; /// @notice ETH token withdrawal gas limit, used only for complete withdrawals uint256 constant ETH_WITHDRAWAL_GAS_LIMIT = 10000; /// @notice Bytes in one chunk uint8 constant CHUNK_BYTES = 11; /// @notice ZKSwap address length uint8 constant ADDRESS_BYTES = 20; uint8 constant PUBKEY_HASH_BYTES = 20; /// @notice Public key bytes length uint8 constant PUBKEY_BYTES = 32; /// @notice Ethereum signature r/s bytes length uint8 constant ETH_SIGN_RS_BYTES = 32; /// @notice Success flag bytes length uint8 constant SUCCESS_FLAG_BYTES = 1; /// @notice Max amount of fee tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0) uint16 constant MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS = 32 - 1; /// @notice start ID for user tokens uint16 constant USER_TOKENS_START_ID = 32; /// @notice Max amount of user tokens registered in the network uint16 constant MAX_AMOUNT_OF_REGISTERED_USER_TOKENS = 16352; /// @notice Max amount of tokens registered in the network uint16 constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 16384 - 1; /// @notice Max account id that could be registered in the network uint32 constant MAX_ACCOUNT_ID = (2 ** 28) - 1; /// @notice Expected average period of block creation uint256 constant BLOCK_PERIOD = 15 seconds; /// @notice ETH blocks verification expectation /// Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN. /// If set to 0 validator can revert blocks at any time. uint256 constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD; uint256 constant NOOP_BYTES = 1 * CHUNK_BYTES; uint256 constant CREATE_PAIR_BYTES = 3 * CHUNK_BYTES; uint256 constant DEPOSIT_BYTES = 4 * CHUNK_BYTES; uint256 constant TRANSFER_TO_NEW_BYTES = 4 * CHUNK_BYTES; uint256 constant PARTIAL_EXIT_BYTES = 5 * CHUNK_BYTES; uint256 constant TRANSFER_BYTES = 2 * CHUNK_BYTES; uint256 constant UNISWAP_ADD_LIQ_BYTES = 3 * CHUNK_BYTES; uint256 constant UNISWAP_RM_LIQ_BYTES = 3 * CHUNK_BYTES; uint256 constant UNISWAP_SWAP_BYTES = 2 * CHUNK_BYTES; /// @notice Full exit operation length uint256 constant FULL_EXIT_BYTES = 4 * CHUNK_BYTES; /// @notice OnchainWithdrawal data length uint256 constant ONCHAIN_WITHDRAWAL_BYTES = 1 + 20 + 2 + 16; // (uint8 addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount) /// @notice ChangePubKey operation length uint256 constant CHANGE_PUBKEY_BYTES = 5 * CHUNK_BYTES; /// @notice Expiration delta for priority request to be satisfied (in seconds) /// NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD), otherwise incorrect block with priority op could not be reverted. uint256 constant PRIORITY_EXPIRATION_PERIOD = 3 days; /// @notice Expiration delta for priority request to be satisfied (in ETH blocks) uint256 constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD / BLOCK_PERIOD; /// @notice Maximum number of priority request to clear during verifying the block /// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots /// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6; /// @notice Reserved time for users to send full exit priority operation in case of an upgrade (in seconds) uint constant MASS_FULL_EXIT_PERIOD = 3 days; /// @notice Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds) uint constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days; /// @notice Notice period before activation preparation status of upgrade mode (in seconds) // NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it. uint constant UPGRADE_NOTICE_PERIOD = MASS_FULL_EXIT_PERIOD + PRIORITY_EXPIRATION_PERIOD + TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT; // @notice Default amount limit for each ERC20 deposit uint128 constant DEFAULT_MAX_DEPOSIT_AMOUNT = 2 ** 85; } pragma solidity ^0.5.0; import "./Upgradeable.sol"; import "./Operations.sol"; /// @title ZKSwap events /// @author Matter Labs /// @author ZKSwap L2 Labs interface Events { /// @notice Event emitted when a block is committed event BlockCommit(uint32 indexed blockNumber); /// @notice Event emitted when a block is verified event BlockVerification(uint32 indexed blockNumber); /// @notice Event emitted when a sequence of blocks is verified event MultiblockVerification(uint32 indexed blockNumberFrom, uint32 indexed blockNumberTo); /// @notice Event emitted when user send a transaction to withdraw her funds from onchain balance event OnchainWithdrawal( address indexed owner, uint16 indexed tokenId, uint128 amount ); /// @notice Event emitted when user send a transaction to deposit her funds event OnchainDeposit( address indexed sender, uint16 indexed tokenId, uint128 amount, address indexed owner ); event OnchainCreatePair( uint16 indexed tokenAId, uint16 indexed tokenBId, uint16 indexed pairId, address pair ); /// @notice Event emitted when user sends a authentication fact (e.g. pub-key hash) event FactAuth( address indexed sender, uint32 nonce, bytes fact ); /// @notice Event emitted when blocks are reverted event BlocksRevert( uint32 indexed totalBlocksVerified, uint32 indexed totalBlocksCommitted ); /// @notice Exodus mode entered event event ExodusMode(); /// @notice New priority request event. Emitted when a request is placed into mapping event NewPriorityRequest( address sender, uint64 serialId, Operations.OpType opType, bytes pubData, bytes userData, uint256 expirationBlock ); /// @notice Deposit committed event. event DepositCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint16 indexed tokenId, uint128 amount ); /// @notice Full exit committed event. event FullExitCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint16 indexed tokenId, uint128 amount ); /// @notice Pending withdrawals index range that were added in the verifyBlock operation. /// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex) event PendingWithdrawalsAdd( uint32 queueStartIndex, uint32 queueEndIndex ); /// @notice Pending withdrawals index range that were executed in the completeWithdrawals operation. /// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex) event PendingWithdrawalsComplete( uint32 queueStartIndex, uint32 queueEndIndex ); event CreatePairCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, uint16 tokenAId, uint16 tokenBId, uint16 indexed tokenPairId, address pair ); } /// @title Upgrade events /// @author Matter Labs interface UpgradeEvents { /// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts event NewUpgradable( uint indexed versionId, address indexed upgradeable ); /// @notice Upgrade mode enter event event NoticePeriodStart( uint indexed versionId, address[] newTargets, uint noticePeriod // notice period (in seconds) ); /// @notice Upgrade mode cancel event event UpgradeCancel( uint indexed versionId ); /// @notice Upgrade mode preparation status event event PreparationStart( uint indexed versionId ); /// @notice Upgrade mode complete event event UpgradeComplete( uint indexed versionId, address[] newTargets ); } pragma solidity ^0.5.0; // Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word) // implements the following algorithm: // f(bytes memory input, uint offset) -> X out // where byte representation of out is N bytes from input at the given offset // 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N] // W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N // 2) We load W from memory into out, last N bytes of W are placed into out library Bytes { function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint(self), 2); } function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint(self), 3); } function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint(self), 4); } function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint(self), 16); } // Copies 'len' lower bytes from 'self' into a new 'bytes memory'. // Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'. function toBytesFromUIntTruncated(uint self, uint8 byteLength) private pure returns (bytes memory bts) { require(byteLength <= 32, "bt211"); bts = new bytes(byteLength); // Even though the bytes will allocate a full word, we don't want // any potential garbage bytes in there. uint data = self << ((32 - byteLength) * 8); assembly { mstore(add(bts, /*BYTES_HEADER_SIZE*/32), data) } } // Copies 'self' into a new 'bytes memory'. // Returns the newly created 'bytes memory'. The returned bytes will be of length '20'. function toBytesFromAddress(address self) internal pure returns (bytes memory bts) { bts = toBytesFromUIntTruncated(uint(self), 20); } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 20) function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) { uint256 offset = _start + 20; require(self.length >= offset, "bta11"); assembly { addr := mload(add(self, offset)) } } // Reasoning about why this function works is similar to that of other similar functions, except NOTE below. // NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types // NOTE: theoretically possible overflow of (_start + 20) function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) { require(self.length >= (_start + 20), "btb20"); assembly { r := mload(add(add(self, 0x20), _start)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x2) function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) { uint256 offset = _start + 0x2; require(_bytes.length >= offset, "btu02"); assembly { r := mload(add(_bytes, offset)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x3) function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) { uint256 offset = _start + 0x3; require(_bytes.length >= offset, "btu03"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x4) function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) { uint256 offset = _start + 0x4; require(_bytes.length >= offset, "btu04"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x10) function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) { uint256 offset = _start + 0x10; require(_bytes.length >= offset, "btu16"); assembly { r := mload(add(_bytes, offset)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x14) function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) { uint256 offset = _start + 0x14; require(_bytes.length >= offset, "btu20"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x20) function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) { uint256 offset = _start + 0x20; require(_bytes.length >= offset, "btb32"); assembly { r := mload(add(_bytes, offset)) } } // Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228 // Get slice from bytes arrays // Returns the newly created 'bytes memory' // NOTE: theoretically possible overflow of (_start + _length) function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "bse11"); // bytes length is less then start byte + length bytes bytes memory tempBytes = new bytes(_length); if (_length != 0) { // TODO: Review this thoroughly. assembly { let slice_curr := add(tempBytes, 0x20) let slice_end := add(slice_curr, _length) for { let array_current := add(_bytes, add(_start, 0x20)) } lt(slice_curr, slice_end) { slice_curr := add(slice_curr, 0x20) array_current := add(array_current, 0x20) } { mstore(slice_curr, mload(array_current)) } } } return tempBytes; } /// Reads byte stream /// @return new_offset - offset + amount of bytes read /// @return data - actually read data // NOTE: theoretically possible overflow of (_offset + _length) function read(bytes memory _data, uint _offset, uint _length) internal pure returns (uint new_offset, bytes memory data) { data = slice(_data, _offset, _length); new_offset = _offset + _length; } // NOTE: theoretically possible overflow of (_offset + 1) function readBool(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bool r) { new_offset = _offset + 1; r = uint8(_data[_offset]) != 0; } // NOTE: theoretically possible overflow of (_offset + 1) function readUint8(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint8 r) { new_offset = _offset + 1; r = uint8(_data[_offset]); } // NOTE: theoretically possible overflow of (_offset + 2) function readUInt16(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint16 r) { new_offset = _offset + 2; r = bytesToUInt16(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 3) function readUInt24(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint24 r) { new_offset = _offset + 3; r = bytesToUInt24(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 4) function readUInt32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint32 r) { new_offset = _offset + 4; r = bytesToUInt32(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 16) function readUInt128(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint128 r) { new_offset = _offset + 16; r = bytesToUInt128(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readUInt160(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint160 r) { new_offset = _offset + 20; r = bytesToUInt160(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readAddress(bytes memory _data, uint _offset) internal pure returns (uint new_offset, address r) { new_offset = _offset + 20; r = bytesToAddress(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readBytes20(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes20 r) { new_offset = _offset + 20; r = bytesToBytes20(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 32) function readBytes32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes32 r) { new_offset = _offset + 32; r = bytesToBytes32(_data, _offset); } // Helper function for hex conversion. function halfByteToHex(byte _byte) internal pure returns (byte _hexByte) { require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range. // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. return byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byte) * 8))); } // Convert bytes to ASCII hex representation function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) { bytes memory outStringBytes = new bytes(_input.length * 2); // code in `assembly` construction is equivalent of the next code: // for (uint i = 0; i < _input.length; ++i) { // outStringBytes[i*2] = halfByteToHex(_input[i] >> 4); // outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f); // } assembly { let input_curr := add(_input, 0x20) let input_end := add(input_curr, mload(_input)) for { let out_curr := add(outStringBytes, 0x20) } lt(input_curr, input_end) { input_curr := add(input_curr, 0x01) out_curr := add(out_curr, 0x02) } { let curr_input_byte := shr(0xf8, mload(input_curr)) // here outStringByte from each half of input byte calculates by the next: // // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. // outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8))) mstore(out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130))) mstore(add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130))) } } return outStringBytes; } /// Trim bytes into single word function trim(bytes memory _data, uint _new_length) internal pure returns (uint r) { require(_new_length <= 0x20, "trm10"); // new_length is longer than word require(_data.length >= _new_length, "trm11"); // data is to short uint a; assembly { a := mload(add(_data, 0x20)) // load bytes into uint256 } return a >> ((0x20 - _new_length) * 8); } } pragma solidity ^0.5.0; import "./Bytes.sol"; /// @title ZKSwap operations tools library Operations { // Circuit ops and their pubdata (chunks * bytes) /// @notice ZKSwap circuit operation type enum OpType { Noop, Deposit, TransferToNew, PartialExit, _CloseAccount, // used for correct op id offset Transfer, FullExit, ChangePubKey, CreatePair, AddLiquidity, RemoveLiquidity, Swap } // Byte lengths uint8 constant TOKEN_BYTES = 2; uint8 constant PUBKEY_BYTES = 32; uint8 constant NONCE_BYTES = 4; uint8 constant PUBKEY_HASH_BYTES = 20; uint8 constant ADDRESS_BYTES = 20; /// @notice Packed fee bytes lengths uint8 constant FEE_BYTES = 2; /// @notice ZKSwap account id bytes lengths uint8 constant ACCOUNT_ID_BYTES = 4; uint8 constant AMOUNT_BYTES = 16; /// @notice Signature (for example full exit signature) bytes length uint8 constant SIGNATURE_BYTES = 64; // Deposit pubdata struct Deposit { uint32 accountId; uint16 tokenId; uint128 amount; address owner; } uint public constant PACKED_DEPOSIT_PUBDATA_BYTES = ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES; /// Deserialize deposit pubdata function readDepositPubdata(bytes memory _data) internal pure returns (Deposit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint offset = 0; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "rdp10"); // reading invalid deposit pubdata size } /// Serialize deposit pubdata function writeDepositPubdata(Deposit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.tokenId, // tokenId op.amount, // amount op.owner // owner ); } /// @notice Check that deposit pubdata from request and block matches function depositPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) { // We must ignore `accountId` because it is present in block pubdata but not in priority queue bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES); bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES); return keccak256(lhs_trimmed) == keccak256(rhs_trimmed); } // FullExit pubdata struct FullExit { uint32 accountId; address owner; uint16 tokenId; uint128 amount; } uint public constant PACKED_FULL_EXIT_PUBDATA_BYTES = ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES; function readFullExitPubdata(bytes memory _data) internal pure returns (FullExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint offset = 0; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "rfp10"); // reading invalid full exit pubdata size } function writeFullExitPubdata(FullExit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( op.accountId, // accountId op.owner, // owner op.tokenId, // tokenId op.amount // amount ); } /// @notice Check that full exit pubdata from request and block matches function fullExitPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) { // `amount` is ignored because it is present in block pubdata but not in priority queue uint lhs = Bytes.trim(_lhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES); uint rhs = Bytes.trim(_rhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES); return lhs == rhs; } // PartialExit pubdata struct PartialExit { //uint32 accountId; -- present in pubdata, ignored at serialization uint16 tokenId; uint128 amount; //uint16 fee; -- present in pubdata, ignored at serialization address owner; } function readPartialExitPubdata(bytes memory _data, uint _offset) internal pure returns (PartialExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint offset = _offset + ACCOUNT_ID_BYTES; // accountId (ignored) (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount } function writePartialExitPubdata(PartialExit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.owner, // owner op.tokenId, // tokenId op.amount // amount ); } // ChangePubKey struct ChangePubKey { uint32 accountId; bytes20 pubKeyHash; address owner; uint32 nonce; } function readChangePubKeyPubdata(bytes memory _data, uint _offset) internal pure returns (ChangePubKey memory parsed) { uint offset = _offset; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce } // Withdrawal data process function readWithdrawalData(bytes memory _data, uint _offset) internal pure returns (bool _addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount) { uint offset = _offset; (offset, _addToPendingWithdrawalsQueue) = Bytes.readBool(_data, offset); (offset, _to) = Bytes.readAddress(_data, offset); (offset, _tokenId) = Bytes.readUInt16(_data, offset); (offset, _amount) = Bytes.readUInt128(_data, offset); } // CreatePair pubdata struct CreatePair { uint32 accountId; uint16 tokenA; uint16 tokenB; uint16 tokenPair; address pair; } uint public constant PACKED_CREATE_PAIR_PUBDATA_BYTES = ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES; function readCreatePairPubdata(bytes memory _data) internal pure returns (CreatePair memory parsed) { uint offset = 0; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId (offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId (offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId (offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size } function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.tokenA, // tokenAId op.tokenB, // tokenBId op.tokenPair, // pairId op.pair // pair account ); } /// @notice Check that create pair pubdata from request and block matches function createPairPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) { // We must ignore `accountId` because it is present in block pubdata but not in priority queue bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES); bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES); return keccak256(lhs_trimmed) == keccak256(rhs_trimmed); } } pragma solidity ^0.5.0; /// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it) /// @author Matter Labs /// @author ZKSwap L2 Labs interface UpgradeableMaster { /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external returns (uint); /// @notice Notifies contract that notice period started function upgradeNoticePeriodStarted() external; /// @notice Notifies contract that upgrade preparation status is activated function upgradePreparationStarted() external; /// @notice Notifies contract that upgrade canceled function upgradeCanceled() external; /// @notice Notifies contract that upgrade finishes function upgradeFinishes() external; /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external returns (bool); } pragma solidity =0.5.16; import './interfaces/IUniswapV2Factory.sol'; import './UniswapV2Pair.sol'; contract UniswapV2Factory is IUniswapV2Factory { mapping(address => mapping(address => address)) public getPair; address[] public allPairs; address public zkSyncAddress; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor() public { } function initialize(bytes calldata data) external { } function setZkSyncAddress(address _zksyncAddress) external { require(zkSyncAddress == address(0), "szsa1"); zkSyncAddress = _zksyncAddress; } /// @notice PairManager contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} function allPairsLength() external view returns (uint) { return allPairs.length; } function createPair(address tokenA, address tokenB) external returns (address pair) { require(msg.sender == zkSyncAddress, 'fcp1'); require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); //require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(UniswapV2Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } require(zkSyncAddress != address(0), 'wzk'); IUniswapV2Pair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function mint(address pair, address to, uint amount) external { require(msg.sender == zkSyncAddress, 'fmt1'); IUniswapV2Pair(pair).mint(to, amount); } function burn(address pair, address to, uint amount) external { require(msg.sender == zkSyncAddress, 'fbr1'); IUniswapV2Pair(pair).burn(to, amount); } } pragma solidity ^0.5.0; contract PairTokenManager { /// @notice Max amount of pair tokens registered in the network. uint16 constant MAX_AMOUNT_OF_PAIR_TOKENS = 49152; uint16 constant PAIR_TOKEN_START_ID = 16384; /// @notice Total number of pair tokens registered in the network uint16 public totalPairTokens; /// @notice List of registered tokens by tokenId mapping(uint16 => address) public tokenAddresses; /// @notice List of registered tokens by address mapping(address => uint16) public tokenIds; /// @notice Token added to Franklin net event NewToken( address indexed token, uint16 indexed tokenId ); function addPairToken(address _token) internal { require(tokenIds[_token] == 0, "pan1"); // token exists require(totalPairTokens < MAX_AMOUNT_OF_PAIR_TOKENS, "pan2"); // no free identifiers for tokens uint16 newPairTokenId = PAIR_TOKEN_START_ID + totalPairTokens; totalPairTokens++; tokenAddresses[newPairTokenId] = _token; tokenIds[_token] = newPairTokenId; emit NewToken(_token, newPairTokenId); } /// @notice Validate pair token address /// @param _tokenAddr Token address /// @return tokens id function validatePairTokenAddress(address _tokenAddr) public view returns (uint16) { uint16 tokenId = tokenIds[_tokenAddr]; require(tokenId != 0, "pms3"); require(tokenId <= (PAIR_TOKEN_START_ID -1 + MAX_AMOUNT_OF_PAIR_TOKENS), "pms4"); return tokenId; } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./Config.sol"; /// @title Governance Contract /// @author Matter Labs /// @author ZKSwap L2 Labs contract Governance is Config { /// @notice Token added to Franklin net event NewToken( address indexed token, uint16 indexed tokenId ); /// @notice Governor changed event NewGovernor( address newGovernor ); /// @notice tokenLister changed event NewTokenLister( address newTokenLister ); /// @notice Validator's status changed event ValidatorStatusUpdate( address indexed validatorAddress, bool isActive ); /// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades address public networkGovernor; /// @notice Total number of ERC20 fee tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0) uint16 public totalFeeTokens; /// @notice Total number of ERC20 user tokens registered in the network uint16 public totalUserTokens; /// @notice List of registered tokens by tokenId mapping(uint16 => address) public tokenAddresses; /// @notice List of registered tokens by address mapping(address => uint16) public tokenIds; /// @notice List of permitted validators mapping(address => bool) public validators; address public tokenLister; constructor() public { networkGovernor = msg.sender; } /// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// _networkGovernor The address of network governor function initialize(bytes calldata initializationParameters) external { require(networkGovernor == address(0), "init0"); (address _networkGovernor, address _tokenLister) = abi.decode(initializationParameters, (address, address)); networkGovernor = _networkGovernor; tokenLister = _tokenLister; } /// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} /// @notice Change current governor /// @param _newGovernor Address of the new governor function changeGovernor(address _newGovernor) external { requireGovernor(msg.sender); require(_newGovernor != address(0), "zero address is passed as _newGovernor"); if (networkGovernor != _newGovernor) { networkGovernor = _newGovernor; emit NewGovernor(_newGovernor); } } /// @notice Change current governor /// @param _newTokenLister Address of the new governor function changeTokenLister(address _newTokenLister) external { requireGovernor(msg.sender); require(_newTokenLister != address(0), "zero address is passed as _newTokenLister"); if (tokenLister != _newTokenLister) { tokenLister = _newTokenLister; emit NewTokenLister(_newTokenLister); } } /// @notice Add fee token to the list of networks tokens /// @param _token Token address function addFeeToken(address _token) external { requireGovernor(msg.sender); require(tokenIds[_token] == 0, "gan11"); // token exists require(totalFeeTokens < MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS, "fee12"); // no free identifiers for tokens require( _token != address(0), "address cannot be zero" ); totalFeeTokens++; uint16 newTokenId = totalFeeTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth tokenAddresses[newTokenId] = _token; tokenIds[_token] = newTokenId; emit NewToken(_token, newTokenId); } /// @notice Add token to the list of networks tokens /// @param _token Token address function addToken(address _token) external { requireTokenLister(msg.sender); require(tokenIds[_token] == 0, "gan11"); // token exists require(totalUserTokens < MAX_AMOUNT_OF_REGISTERED_USER_TOKENS, "gan12"); // no free identifiers for tokens require( _token != address(0), "address cannot be zero" ); uint16 newTokenId = USER_TOKENS_START_ID + totalUserTokens; totalUserTokens++; tokenAddresses[newTokenId] = _token; tokenIds[_token] = newTokenId; emit NewToken(_token, newTokenId); } /// @notice Change validator status (active or not active) /// @param _validator Validator address /// @param _active Active flag function setValidator(address _validator, bool _active) external { requireGovernor(msg.sender); if (validators[_validator] != _active) { validators[_validator] = _active; emit ValidatorStatusUpdate(_validator, _active); } } /// @notice Check if specified address is is governor /// @param _address Address to check function requireGovernor(address _address) public view { require(_address == networkGovernor, "grr11"); // only by governor } /// @notice Check if specified address can list token /// @param _address Address to check function requireTokenLister(address _address) public view { require(_address == networkGovernor || _address == tokenLister, "grr11"); // token lister or governor } /// @notice Checks if validator is active /// @param _address Validator address function requireActiveValidator(address _address) external view { require(validators[_address], "grr21"); // validator is not active } /// @notice Validate token id (must be less than or equal to total tokens amount) /// @param _tokenId Token id /// @return bool flag that indicates if token id is less than or equal to total tokens amount function isValidTokenId(uint16 _tokenId) external view returns (bool) { return (_tokenId <= totalFeeTokens) || (_tokenId >= USER_TOKENS_START_ID && _tokenId < (USER_TOKENS_START_ID + totalUserTokens )); } /// @notice Validate token address /// @param _tokenAddr Token address /// @return tokens id function validateTokenAddress(address _tokenAddr) external view returns (uint16) { uint16 tokenId = tokenIds[_tokenAddr]; require(tokenId != 0, "gvs11"); // 0 is not a valid token require(tokenId <= MAX_AMOUNT_OF_REGISTERED_TOKENS, "gvs12"); return tokenId; } function getTokenAddress(uint16 _tokenId) external view returns (address) { address tokenAddr = tokenAddresses[_tokenId]; return tokenAddr; } } pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./KeysWithPlonkAggVerifier.sol"; // Hardcoded constants to avoid accessing store contract Verifier is KeysWithPlonkAggVerifier { bool constant DUMMY_VERIFIER = false; function initialize(bytes calldata) external { } /// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} function isBlockSizeSupported(uint32 _size) public pure returns (bool) { if (DUMMY_VERIFIER) { return true; } else { return isBlockSizeSupportedInternal(_size); } } function verifyMultiblockProof( uint256[] calldata _recursiveInput, uint256[] calldata _proof, uint32[] calldata _block_sizes, uint256[] calldata _individual_vks_inputs, uint256[] calldata _subproofs_limbs ) external view returns (bool) { if (DUMMY_VERIFIER) { uint oldGasValue = gasleft(); uint tmp; while (gasleft() + 500000 > oldGasValue) { tmp += 1; } return true; } uint8[] memory vkIndexes = new uint8[](_block_sizes.length); for (uint32 i = 0; i < _block_sizes.length; i++) { vkIndexes[i] = blockSizeToVkIndex(_block_sizes[i]); } VerificationKey memory vk = getVkAggregated(uint32(_block_sizes.length)); return verify_serialized_proof_with_recursion(_recursiveInput, _proof, VK_TREE_ROOT, VK_MAX_INDEX, vkIndexes, _individual_vks_inputs, _subproofs_limbs, vk); } } pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./KeysWithPlonkSingleVerifier.sol"; // Hardcoded constants to avoid accessing store contract VerifierExit is KeysWithPlonkSingleVerifier { function initialize(bytes calldata) external { } /// @notice VerifierExit contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} function verifyExitProof( bytes32 _rootHash, uint32 _accountId, address _owner, uint16 _tokenId, uint128 _amount, uint256[] calldata _proof ) external view returns (bool) { bytes32 commitment = sha256(abi.encodePacked(_rootHash, _accountId, _owner, _tokenId, _amount)); uint256[] memory inputs = new uint256[](1); uint256 mask = (~uint256(0)) >> 3; inputs[0] = uint256(commitment) & mask; Proof memory proof = deserialize_proof(inputs, _proof); VerificationKey memory vk = getVkExit(); require(vk.num_inputs == inputs.length); return verify(proof, vk); } function concatBytes(bytes memory param1, bytes memory param2) public pure returns (bytes memory) { bytes memory merged = new bytes(param1.length + param2.length); uint k = 0; for (uint i = 0; i < param1.length; i++) { merged[k] = param1[i]; k++; } for (uint i = 0; i < param2.length; i++) { merged[k] = param2[i]; k++; } return merged; } function verifyLpExitProof( bytes calldata _account_data, bytes calldata _pair_data0, bytes calldata _pair_data1, uint256[] calldata _proof ) external view returns (bool) { bytes memory _data1 = concatBytes(_account_data, _pair_data0); bytes memory _data2 = concatBytes(_data1, _pair_data1); bytes32 commitment = sha256(_data2); uint256[] memory inputs = new uint256[](1); uint256 mask = (~uint256(0)) >> 3; inputs[0] = uint256(commitment) & mask; Proof memory proof = deserialize_proof(inputs, _proof); VerificationKey memory vk = getVkLpExit(); require(vk.num_inputs == inputs.length); return verify(proof, vk); } } pragma solidity ^0.5.0; /// @title Interface of the upgradeable contract /// @author Matter Labs /// @author ZKSwap L2 Labs interface Upgradeable { /// @notice Upgrades target of upgradeable contract /// @param newTarget New target /// @param newTargetInitializationParameters New target initialization parameters function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external; } pragma solidity >=0.5.0; 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 allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); } pragma solidity =0.5.16; import './interfaces/IUniswapV2Pair.sol'; import './UniswapV2ERC20.sol'; import './libraries/Math.sol'; import './libraries/UQ112x112.sol'; import './interfaces/IUNISWAPERC20.sol'; import './interfaces/IUniswapV2Factory.sol'; import './interfaces/IUniswapV2Callee.sol'; contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 { using UniswapSafeMath for uint; using UQ112x112 for uint224; address public factory; address public token0; address public token1; uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'UniswapV2: LOCKED'); unlocked = 0; _; unlocked = 1; } constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } function mint(address to, uint amount) external lock { require(msg.sender == factory, 'mt1'); _mint(to, amount); } function burn(address to, uint amount) external lock { require(msg.sender == factory, 'br1'); _burn(to, amount); } } pragma solidity >=0.5.0 <0.7.0; pragma experimental ABIEncoderV2; import "./PlonkAggCore.sol"; // Hardcoded constants to avoid accessing store contract KeysWithPlonkAggVerifier is AggVerifierWithDeserialize { uint256 constant VK_TREE_ROOT = 0x0a3cdc9655e61bf64758c1e8df745723e9b83addd4f0d0f2dd65dc762dc1e9e7; uint8 constant VK_MAX_INDEX = 5; function isBlockSizeSupportedInternal(uint32 _size) internal pure returns (bool) { if (_size == uint32(6)) { return true; } else if (_size == uint32(12)) { return true; } else if (_size == uint32(48)) { return true; } else if (_size == uint32(96)) { return true; } else if (_size == uint32(204)) { return true; } else if (_size == uint32(420)) { return true; } else { return false; } } function blockSizeToVkIndex(uint32 _chunks) internal pure returns (uint8) { if (_chunks == uint32(6)) { return 0; } else if (_chunks == uint32(12)) { return 1; } else if (_chunks == uint32(48)) { return 2; } else if (_chunks == uint32(96)) { return 3; } else if (_chunks == uint32(204)) { return 4; } else if (_chunks == uint32(420)) { return 5; } } function getVkAggregated(uint32 _blocks) internal pure returns (VerificationKey memory vk) { if (_blocks == uint32(1)) { return getVkAggregated1(); } else if (_blocks == uint32(5)) { return getVkAggregated5(); } } function getVkAggregated1() internal pure returns(VerificationKey memory vk) { vk.domain_size = 4194304; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b, 0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48 ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e, 0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0 ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5, 0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123 ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7, 0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346 ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263, 0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39 ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474, 0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927, 0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37 ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c, 0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951, 0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3, 0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26 ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6, 0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899, 0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1, 0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59 ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } function getVkAggregated5() internal pure returns(VerificationKey memory vk) { vk.domain_size = 16777216; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x023cfc69ef1b002da66120fce352ede75893edd8cd8196403a54e1eceb82cd43, 0x2baf3bd673e46be9df0d43ca30f834671543c22db422f450b2efd8c931e9b34e ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x23783fe0e5c3f83c02c864e25fe766afb727134c9a77ae6b9694efb7b46f31ab, 0x1903d01005e447d061c16323a1d604d8fbd4b5cc9b64945a71f1234d280c4d3a ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x2897df6c6fa993661b2b0b0cf52460278e33533de71b3c0f7ed7c1f20af238c6, 0x042344afee0aed5505e59bce4ebbe942a91268a8af6b77ea95f603b5b726e8cb ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x0fceed33e78426afc38d8a68c0d93413d2bbaa492b087125271d33d52bdb07b8, 0x0057e4f63be36edb56e91da931f3d0ba72d1862d4b7751c59b92b6ae9f1fcc11 ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x14230a35f172cd77a2147cecc20b2a13148363cbab78709489a29d08001e26fb, 0x04f1040477d77896475080b5abb8091cda2cce4917ee0ba5dd62d0ab1be379b4 ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x20d1a079ad80a8abb7fd8ba669dddbbe23231360a5f0ba679b6536b6bf980649, 0x120c5a845903bd6de4105eb8cef90e6dff2c3888ada16c90e1efb393778d6a4d ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x1af6b9e362e458a96b8bbbf8f8ce2bdbd650fb68478360c408a2acf1633c1ce1, 0x27033728b767b44c659e7896a6fcc956af97566a5a1135f87a2e510976a62d41 ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x0dbfb3c5f5131eb6f01e12b1a6333b0ad22cc8292b666e46e9bd4d80802cccdf, 0x2d058711c42fd2fd2eef33fb327d111a27fe2063b46e1bb54b32d02e9676e546 ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x0c8c7352a84dd3f32412b1a96acd94548a292411fd7479d8609ca9bd872f1e36, 0x0874203fd8012d6976698cc2df47bca14bc04879368ade6412a2109c1e71e5e8 ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x1b17bb7c319b1cf15461f4f0b69d98e15222320cb2d22f4e3a5f5e0e9e51f4bd, 0x0cf5bc338235ded905926006027aa2aab277bc32a098cd5b5353f5545cbd2825 ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x0794d3cfbc2fdd756b162571a40e40b8f31e705c77063f30a4e9155dbc00e0ef, 0x1f821232ab8826ea5bf53fe9866c74e88a218c8d163afcaa395eda4db57b7a23 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x224d93783aa6856621a9bbec495f4830c94994e266b240db9d652dbb394a283b, 0x161bcec99f3bc449d655c0ca59874dafe1194138eec91af34392b09a83338ca1 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x1fa27e2916b2c11d39c74c0e61063190da31c102d2b7da5c0a61ec8c5e82f132, 0x0a815ee76cd8aa600e6f66463b25a0ee57814bfdf06c65a91ddc70cede41caae ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } } pragma solidity >=0.5.0 <0.7.0; import "./PlonkSingleCore.sol"; // Hardcoded constants to avoid accessing store contract KeysWithPlonkSingleVerifier is SingleVerifierWithDeserialize { function isBlockSizeSupportedInternal(uint32 _size) internal pure returns (bool) { if (_size == uint32(6)) { return true; } else if (_size == uint32(12)) { return true; } else if (_size == uint32(48)) { return true; } else if (_size == uint32(96)) { return true; } else if (_size == uint32(204)) { return true; } else if (_size == uint32(420)) { return true; } else { return false; } } function getVkExit() internal pure returns(VerificationKey memory vk) { vk.domain_size = 262144; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe); vk.selector_commitments[0] = PairingsBn254.new_g1( 0x1abc710835cdc78389d61b670b0e8d26416a63c9bd3d6ed435103ebbb8a8665e, 0x138c6678230ed19f90b947d0a9027bd9fc458bbd1d2b8371fa72e28470a97b9c ); vk.selector_commitments[1] = PairingsBn254.new_g1( 0x28d81ac76e1ddf630b4bf8e4a789cf9c4470c5e5cc010a24849b20ab595b8b22, 0x251ca3cf0829b261d3be8d6cbd25aa97d9af716819c29f6319d806f075e79655 ); vk.selector_commitments[2] = PairingsBn254.new_g1( 0x1504c8c227833a1152f3312d258412c334ac7ae213e21427ff63028729bc28fa, 0x0f0942f3fede795cbe624fb9ddf9be90ba546609383f2246c3c9b92af7aab5fd ); vk.selector_commitments[3] = PairingsBn254.new_g1( 0x1f14a5bb19ea2897ac6b9fbdbd2b4e371be09f8e90a47ae26602d399c9bcd311, 0x029c6ea094247da75d9a66cea627c3c77d48b898003125d4f8e785435dc2cf23 ); vk.selector_commitments[4] = PairingsBn254.new_g1( 0x102cdd83e2d70638a70d700622b662607f8a2d92f5c36053a4ddb4b600d75bcf, 0x09ef3679579d761507ef69eaf49c978b271f0e4500468da1ebd7197f3ff5d6ac ); vk.selector_commitments[5] = PairingsBn254.new_g1( 0x2c2bd1d2fa3d4b3915d0fe465469e11ee563e79751da71c6082fcd0ca4e41cd5, 0x0304f16147a8af177dcc703370931d5161bda9dcf3e091787b9a54377ab54c32 ); // we only have access to value of the d(x) witness polynomial on the next // trace step, so we only need one element here and deal with it in other places // by having this in mind vk.next_step_selector_commitments[0] = PairingsBn254.new_g1( 0x14420680f992f4bc8d8012e2d8b14a774cf9114adf1e41b3c02c20cc1648398e, 0x237d3d5cdee5e3d7d58f4eb336ecd7aa5ec88d89205861b410420f6b9f6b26a1 ); vk.permutation_commitments[0] = PairingsBn254.new_g1( 0x221045ae5578ccb35e0a198d83c0fb191da8cdc98423fc46e580f1762682c73e, 0x15b7f3d74fcd258fdd2ae6001693a7c615e654d613a506d213aaf0ad314e338d ); vk.permutation_commitments[1] = PairingsBn254.new_g1( 0x03e47981b459b3be258a6353593898babec571ccf3e0362d53a67f078f04830a, 0x0809556ab6eb28403bb5a749fcdbd8656940add7685ff5473dc3a9ad940034df ); vk.permutation_commitments[2] = PairingsBn254.new_g1( 0x2c02322c53d7e6a6474b15c7db738419e3f4d1263e9f98ebb56c24906f555ef9, 0x2322c69f51366551665b584d797e0fdadb16fe31b1e7ae2f532847a75b3aeaab ); vk.permutation_commitments[3] = PairingsBn254.new_g1( 0x2147e39b49c2bef4168884c0ac9e38bb4dc65b41ba21953f7ded2daab7fe1534, 0x071f3548c9ca2c6a8d10b11d553263ebe0afaf1f663b927ef970bd6c3974cb68 ); vk.permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } function getVkLpExit() internal pure returns(VerificationKey memory vk) { vk.domain_size = 524288; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x0cf1526aaafac6bacbb67d11a4077806b123f767e4b0883d14cc0193568fc082); vk.selector_commitments[0] = PairingsBn254.new_g1( 0x067d967299b3d380f2e461409fbacb82d9af8c85b62de082a423f344fb0b9d38, 0x2440bd569ac24e9525b29e433334ee98d72cb8eb19af65250ee0099fb470d873 ); vk.selector_commitments[1] = PairingsBn254.new_g1( 0x086a9ed0f6175964593e516a8c1fc8bbd0a9c8afb724ebbce08a7772bd7b8837, 0x0aca3794dc6a2f0cab69dfed529d31deb7a5e9e6c339e3c07d8d88df0f7abd6b ); vk.selector_commitments[2] = PairingsBn254.new_g1( 0x00b6bfec3aceb55618e6caf637c978c3fe2344568c64515022fcfa00e490eb97, 0x0f890fe6b9cb943fb4887df1529cdae99e2494eabf675f89905215eb51c29c6e ); vk.selector_commitments[3] = PairingsBn254.new_g1( 0x0968470be841bcbfbcccc10dd0d8b63a871cdb3289c214fc59f38c88ab15146a, 0x1a9b4d034050fa0b119bb64ba0e967fd09f224c6fd9cd8b54cd6f081085dfb98 ); vk.selector_commitments[4] = PairingsBn254.new_g1( 0x080dbe10de0cacf12db303a86049c7a4d42f068a9def099e0cb874008f210b1b, 0x02f17638d3410ab573e33a4e6c6cf0c918bea2aa4f1025ca5ee13d7a950c4058 ); vk.selector_commitments[5] = PairingsBn254.new_g1( 0x267043dbe00520bd8bbf55a96b51fde6b3b64219eca9e2fd8309693db0cf0392, 0x08dbbfa17faad841228af22a03fab7ec20f765036a2acae62f543f61e55b6e8c ); // we only have access to value of the d(x) witness polynomial on the next // trace step, so we only need one element here and deal with it in other places // by having this in mind vk.next_step_selector_commitments[0] = PairingsBn254.new_g1( 0x215141775449677e3dbe25ff6c5e5d99336a29d952a61d5ec87618346e78df30, 0x29502caeb6afaf2acd13766d52fac2907efb7d11c66cd8beb93c8321d380b215 ); vk.permutation_commitments[0] = PairingsBn254.new_g1( 0x150790105b9f5455ae6f91daa6b03c5793fb7bcfcd9d5d37d3b643b77535b10a, 0x2b644a9736282f80fae8d35f00cbddf2bba3560c54f3d036ec1c8014c147a506 ); vk.permutation_commitments[1] = PairingsBn254.new_g1( 0x1b898666ded092a449935de7d707ad8d65809c2baccdd7dd7cfdaf2fb27e1262, 0x2a24c241dcad93b7bdf1cce2427c9c54f731a7d50c27a825e2af3dabb66dc81f ); vk.permutation_commitments[2] = PairingsBn254.new_g1( 0x049892634dbbfa0c364523827cd7e604b70a7e24a4cb111cb8fccb7c05b04d7f, 0x1e5d8d7c0bf92d822dcf339a52c326a35cadf010b888b8f26e155a68c7e23dc9 ); vk.permutation_commitments[3] = PairingsBn254.new_g1( 0x04f90846cb1598aa05164a78d171ea918154414652d07d3f5cab84a26e6aa158, 0x0975ba8858f136bb8b1b043daf8dfed33709f72ba37e01e5de62c81f3928a13c ); vk.permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } } 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 factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function initialize(address, address) external; function mint(address to, uint amount) external; function burn(address to, uint amount) external; } pragma solidity =0.5.16; import './interfaces/IUniswapV2ERC20.sol'; import './libraries/UniswapSafeMath.sol'; contract UniswapV2ERC20 is IUniswapV2ERC20 { using UniswapSafeMath for uint; string public constant name = 'ZKSWAP V2'; string public constant symbol = 'ZKS-V2'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid } } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } } pragma solidity =0.5.16; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } pragma solidity =0.5.16; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } pragma solidity >=0.5.0; interface IUNISWAPERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } pragma solidity >=0.5.0 <0.7.0; pragma experimental ABIEncoderV2; import "./PlonkCoreLib.sol"; contract Plonk4AggVerifierWithAccessToDNext { uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617; using PairingsBn254 for PairingsBn254.G1Point; using PairingsBn254 for PairingsBn254.G2Point; using PairingsBn254 for PairingsBn254.Fr; using TranscriptLibrary for TranscriptLibrary.Transcript; uint256 constant ZERO = 0; uint256 constant ONE = 1; uint256 constant TWO = 2; uint256 constant THREE = 3; uint256 constant FOUR = 4; uint256 constant STATE_WIDTH = 4; uint256 constant NUM_DIFFERENT_GATES = 2; uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7; uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0; uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1; uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1; uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK = 0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant LIMB_WIDTH = 68; struct VerificationKey { uint256 domain_size; uint256 num_inputs; PairingsBn254.Fr omega; PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments; PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments; PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments; PairingsBn254.Fr[STATE_WIDTH-1] copy_permutation_non_residues; PairingsBn254.G2Point g2_x; } struct Proof { uint256[] input_values; PairingsBn254.G1Point[STATE_WIDTH] wire_commitments; PairingsBn254.G1Point copy_permutation_grand_product_commitment; PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments; PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z; PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega; PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z; PairingsBn254.Fr copy_grand_product_at_z_omega; PairingsBn254.Fr quotient_polynomial_at_z; PairingsBn254.Fr linearization_polynomial_at_z; PairingsBn254.Fr[STATE_WIDTH-1] permutation_polynomials_at_z; PairingsBn254.G1Point opening_at_z_proof; PairingsBn254.G1Point opening_at_z_omega_proof; } struct PartialVerifierState { PairingsBn254.Fr alpha; PairingsBn254.Fr beta; PairingsBn254.Fr gamma; PairingsBn254.Fr v; PairingsBn254.Fr u; PairingsBn254.Fr z; PairingsBn254.Fr[] cached_lagrange_evals; } function evaluate_lagrange_poly_out_of_domain( uint256 poly_num, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { require(poly_num < domain_size); PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory omega_power = omega.pow(poly_num); res = at.pow(domain_size); res.sub_assign(one); require(res.value != 0); // Vanishing polynomial can not be zero at point `at` res.mul_assign(omega_power); PairingsBn254.Fr memory den = PairingsBn254.copy(at); den.sub_assign(omega_power); den.mul_assign(PairingsBn254.new_fr(domain_size)); den = den.inverse(); res.mul_assign(den); } function evaluate_vanishing( uint256 domain_size, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { res = at.pow(domain_size); res.sub_assign(PairingsBn254.new_fr(1)); } function verify_at_z( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z); require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain lhs.mul_assign(proof.quotient_polynomial_at_z); PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z); // public inputs PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0); PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0); for (uint256 i = 0; i < proof.input_values.length; i++) { tmp.assign(state.cached_lagrange_evals[i]); tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i])); inputs_term.add_assign(tmp); } inputs_term.mul_assign(proof.gate_selector_values_at_z[0]); rhs.add_assign(inputs_term); // now we need 5th power quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp.assign(proof.permutation_polynomials_at_z[i]); tmp.mul_assign(state.beta); tmp.add_assign(state.gamma); tmp.add_assign(proof.wire_values_at_z[i]); z_part.mul_assign(tmp); } tmp.assign(state.gamma); // we need a wire value of the last polynomial in enumeration tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]); z_part.mul_assign(tmp); z_part.mul_assign(quotient_challenge); rhs.sub_assign(z_part); quotient_challenge.mul_assign(state.alpha); tmp.assign(state.cached_lagrange_evals[0]); tmp.mul_assign(quotient_challenge); rhs.sub_assign(tmp); return lhs.value == rhs.value; } function add_contribution_from_range_constraint_gates( PartialVerifierState memory state, Proof memory proof, PairingsBn254.Fr memory current_alpha ) internal pure returns (PairingsBn254.Fr memory res) { // now add contribution from range constraint gate // we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {}) PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE); PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO); PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE); PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR); res = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0); for (uint256 i = 0; i < 3; i++) { current_alpha.mul_assign(state.alpha); // high - 4*low // this is 4*low t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]); t0.mul_assign(four_fr); // high t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]); t1.sub_assign(t0); // t0 is now t1 - {0,1,2,3} // first unroll manually for -0; t2 = PairingsBn254.copy(t1); // -1 t0 = PairingsBn254.copy(t1); t0.sub_assign(one_fr); t2.mul_assign(t0); // -2 t0 = PairingsBn254.copy(t1); t0.sub_assign(two_fr); t2.mul_assign(t0); // -3 t0 = PairingsBn254.copy(t1); t0.sub_assign(three_fr); t2.mul_assign(t0); t2.mul_assign(current_alpha); res.add_assign(t2); } // now also d_next - 4a current_alpha.mul_assign(state.alpha); // high - 4*low // this is 4*low t0 = PairingsBn254.copy(proof.wire_values_at_z[0]); t0.mul_assign(four_fr); // high t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]); t1.sub_assign(t0); // t0 is now t1 - {0,1,2,3} // first unroll manually for -0; t2 = PairingsBn254.copy(t1); // -1 t0 = PairingsBn254.copy(t1); t0.sub_assign(one_fr); t2.mul_assign(t0); // -2 t0 = PairingsBn254.copy(t1); t0.sub_assign(two_fr); t2.mul_assign(t0); // -3 t0 = PairingsBn254.copy(t1); t0.sub_assign(three_fr); t2.mul_assign(t0); t2.mul_assign(current_alpha); res.add_assign(t2); return res; } function reconstruct_linearization_commitment( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point memory res) { // we compute what power of v is used as a delinearization factor in batch opening of // commitments. Let's label W(x) = 1 / (x - z) * // [ // t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z) // + v (r(x) - r(z)) // + v^{2..5} * (witness(x) - witness(z)) // + v^{6} * (selector(x) - selector(z)) // + v^{7..9} * (permutation(x) - permutation(z)) // ] // W'(x) = 1 / (x - z*omega) * // [ // + v^10 (z(x) - z(z*omega)) <- we need this power // + v^11 * (d(x) - d(z*omega)) // ] // // we reconstruct linearization polynomial virtual selector // for that purpose we first linearize over main gate (over all it's selectors) // and multiply them by value(!) of the corresponding main gate selector res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x) PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0); // addition gates for (uint256 i = 0; i < STATE_WIDTH; i++) { tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]); res.point_add_assign(tmp_g1); } // multiplication gate tmp_fr.assign(proof.wire_values_at_z[0]); tmp_fr.mul_assign(proof.wire_values_at_z[1]); tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr); res.point_add_assign(tmp_g1); // d_next tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH+2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x) res.point_add_assign(tmp_g1); // multiply by main gate selector(z) res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE); // calculate scalar contribution from the range check gate tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha); tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar res.point_add_assign(tmp_g1); // proceed as normal to copy permutation current_alpha.mul_assign(state.alpha); // alpha^5 PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha); // z * non_res * beta + gamma + a PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z); grand_product_part_at_z.mul_assign(state.beta); grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]); grand_product_part_at_z.add_assign(state.gamma); for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) { tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]); tmp_fr.mul_assign(state.beta); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i+1]); grand_product_part_at_z.mul_assign(tmp_fr); } grand_product_part_at_z.mul_assign(alpha_for_grand_product); // alpha^n & L_{0}(z), and we bump current_alpha current_alpha.mul_assign(state.alpha); tmp_fr.assign(state.cached_lagrange_evals[0]); tmp_fr.mul_assign(current_alpha); grand_product_part_at_z.add_assign(tmp_fr); // prefactor for grand_product(x) is complete // add to the linearization a part from the term // - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X) PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp_fr.assign(state.beta); tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i]); last_permutation_part_at_z.mul_assign(tmp_fr); } last_permutation_part_at_z.mul_assign(state.beta); last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega); last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument // actually multiply prefactors by z(x) and perm_d(x) and combine them tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z); tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z)); res.point_add_assign(tmp_g1); // multiply them by v immedately as linearization has a factor of v^1 res.point_mul_assign(state.v); // res now contains contribution from the gates linearization and // copy permutation part // now we need to add a part that is the rest // for z(x*omega): // - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega) } function aggregate_commitments( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point[2] memory res) { PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk); PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1); for (uint i = 1; i < proof.quotient_poly_commitments.length; i++) { tmp_fr.mul_assign(z_in_domain_size); tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); commitment_aggregation.point_add_assign(d); for (uint i = 0; i < proof.wire_commitments.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.gate_selector_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint i = 0; i < vk.copy_permutation_commitments.length - 1; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); // now do prefactor for grand_product(x*omega) tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr)); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); // collect opening values aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.linearization_polynomial_at_z); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); for (uint i = 0; i < proof.wire_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint i = 0; i < proof.gate_selector_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.gate_selector_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint i = 0; i < proof.permutation_polynomials_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.permutation_polynomials_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.copy_grand_product_at_z_omega); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z_omega[0]); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value)); PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation; pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z)); tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.omega); tmp_fr.mul_assign(state.u); pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr)); PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u); pair_with_x.point_add_assign(proof.opening_at_z_proof); pair_with_x.negate(); res[0] = pair_with_generator; res[1] = pair_with_x; return res; } function verify_initial( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { require(proof.input_values.length == vk.num_inputs); require(vk.num_inputs == 1); TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); for (uint256 i = 0; i < vk.num_inputs; i++) { transcript.update_with_u256(proof.input_values[i]); } for (uint256 i = 0; i < proof.wire_commitments.length; i++) { transcript.update_with_g1(proof.wire_commitments[i]); } state.beta = transcript.get_challenge(); state.gamma = transcript.get_challenge(); transcript.update_with_g1(proof.copy_permutation_grand_product_commitment); state.alpha = transcript.get_challenge(); for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) { transcript.update_with_g1(proof.quotient_poly_commitments[i]); } state.z = transcript.get_challenge(); state.cached_lagrange_evals = new PairingsBn254.Fr[](1); state.cached_lagrange_evals[0] = evaluate_lagrange_poly_out_of_domain( 0, vk.domain_size, vk.omega, state.z ); bool valid = verify_at_z(state, proof, vk); if (valid == false) { return false; } transcript.update_with_fr(proof.quotient_polynomial_at_z); for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { transcript.update_with_fr(proof.wire_values_at_z[i]); } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { transcript.update_with_fr(proof.wire_values_at_z_omega[i]); } transcript.update_with_fr(proof.gate_selector_values_at_z[0]); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { transcript.update_with_fr(proof.permutation_polynomials_at_z[i]); } transcript.update_with_fr(proof.copy_grand_product_at_z_omega); transcript.update_with_fr(proof.linearization_polynomial_at_z); state.v = transcript.get_challenge(); transcript.update_with_g1(proof.opening_at_z_proof); transcript.update_with_g1(proof.opening_at_z_omega_proof); state.u = transcript.get_challenge(); return true; } // This verifier is for a PLONK with a state width 4 // and main gate equation // q_a(X) * a(X) + // q_b(X) * b(X) + // q_c(X) * c(X) + // q_d(X) * d(X) + // q_m(X) * a(X) * b(X) + // q_constants(X)+ // q_d_next(X) * d(X*omega) // where q_{}(X) are selectors a, b, c, d - state (witness) polynomials // q_d_next(X) "peeks" into the next row of the trace, so it takes // the same d(X) polynomial, but shifted function aggregate_for_verification(Proof memory proof, VerificationKey memory vk) internal view returns (bool valid, PairingsBn254.G1Point[2] memory part) { PartialVerifierState memory state; valid = verify_initial(state, proof, vk); if (valid == false) { return (valid, part); } part = aggregate_commitments(state, proof, vk); (valid, part); } function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) { (bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk); if (valid == false) { return false; } valid = PairingsBn254.pairingProd2(recursive_proof_part[0], PairingsBn254.P2(), recursive_proof_part[1], vk.g2_x); return valid; } function verify_recursive( Proof memory proof, VerificationKey memory vk, uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[] memory subproofs_limbs ) internal view returns (bool) { (uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) = reconstruct_recursive_public_input( recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs ); assert(recursive_input == proof.input_values[0]); (bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk); if (valid == false) { return false; } // aggregated_g1s = inner // recursive_proof_part = outer PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part); valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x); return valid; } function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer) internal view returns (PairingsBn254.G1Point[2] memory result) { // reuse the transcript primitive TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); transcript.update_with_g1(inner[0]); transcript.update_with_g1(inner[1]); transcript.update_with_g1(outer[0]); transcript.update_with_g1(outer[1]); PairingsBn254.Fr memory challenge = transcript.get_challenge(); // 1 * inner + challenge * outer result[0] = PairingsBn254.copy_g1(inner[0]); result[1] = PairingsBn254.copy_g1(inner[1]); PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge); result[0].point_add_assign(tmp); tmp = outer[1].point_mul(challenge); result[1].point_add_assign(tmp); return result; } function reconstruct_recursive_public_input( uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[] memory subproofs_aggregated ) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) { assert(recursive_vks_indexes.length == individual_vks_inputs.length); bytes memory concatenated = abi.encodePacked(recursive_vks_root); uint8 index; for (uint256 i = 0; i < recursive_vks_indexes.length; i++) { index = recursive_vks_indexes[i]; assert(index <= max_valid_index); concatenated = abi.encodePacked(concatenated, index); } uint256 input; for (uint256 i = 0; i < recursive_vks_indexes.length; i++) { input = individual_vks_inputs[i]; assert(input < r_mod); concatenated = abi.encodePacked(concatenated, input); } concatenated = abi.encodePacked(concatenated, subproofs_aggregated); bytes32 commitment = sha256(concatenated); recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK; reconstructed_g1s[0] = PairingsBn254.new_g1_checked( subproofs_aggregated[0] + (subproofs_aggregated[1] << LIMB_WIDTH) + (subproofs_aggregated[2] << 2*LIMB_WIDTH) + (subproofs_aggregated[3] << 3*LIMB_WIDTH), subproofs_aggregated[4] + (subproofs_aggregated[5] << LIMB_WIDTH) + (subproofs_aggregated[6] << 2*LIMB_WIDTH) + (subproofs_aggregated[7] << 3*LIMB_WIDTH) ); reconstructed_g1s[1] = PairingsBn254.new_g1_checked( subproofs_aggregated[8] + (subproofs_aggregated[9] << LIMB_WIDTH) + (subproofs_aggregated[10] << 2*LIMB_WIDTH) + (subproofs_aggregated[11] << 3*LIMB_WIDTH), subproofs_aggregated[12] + (subproofs_aggregated[13] << LIMB_WIDTH) + (subproofs_aggregated[14] << 2*LIMB_WIDTH) + (subproofs_aggregated[15] << 3*LIMB_WIDTH) ); return (recursive_input, reconstructed_g1s); } } contract AggVerifierWithDeserialize is Plonk4AggVerifierWithAccessToDNext { uint256 constant SERIALIZED_PROOF_LENGTH = 34; function deserialize_proof( uint256[] memory public_inputs, uint256[] memory serialized_proof ) internal pure returns(Proof memory proof) { require(serialized_proof.length == SERIALIZED_PROOF_LENGTH); proof.input_values = new uint256[](public_inputs.length); for (uint256 i = 0; i < public_inputs.length; i++) { proof.input_values[i] = public_inputs[i]; } uint256 j = 0; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; } proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; } for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_values_at_z[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) { proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; proof.quotient_polynomial_at_z = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; proof.linearization_polynomial_at_z = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; proof.opening_at_z_proof = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); } function verify_serialized_proof( uint256[] memory public_inputs, uint256[] memory serialized_proof, VerificationKey memory vk ) public view returns (bool) { require(vk.num_inputs == public_inputs.length); Proof memory proof = deserialize_proof(public_inputs, serialized_proof); bool valid = verify(proof, vk); return valid; } function verify_serialized_proof_with_recursion( uint256[] memory public_inputs, uint256[] memory serialized_proof, uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[] memory subproofs_limbs, VerificationKey memory vk ) public view returns (bool) { require(vk.num_inputs == public_inputs.length); Proof memory proof = deserialize_proof(public_inputs, serialized_proof); bool valid = verify_recursive(proof, vk, recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs); return valid; } } pragma solidity >=0.5.0 <0.7.0; import "./PlonkCoreLib.sol"; contract Plonk4SingleVerifierWithAccessToDNext { using PairingsBn254 for PairingsBn254.G1Point; using PairingsBn254 for PairingsBn254.G2Point; using PairingsBn254 for PairingsBn254.Fr; using TranscriptLibrary for TranscriptLibrary.Transcript; uint256 constant STATE_WIDTH = 4; uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1; struct VerificationKey { uint256 domain_size; uint256 num_inputs; PairingsBn254.Fr omega; PairingsBn254.G1Point[STATE_WIDTH+2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] next_step_selector_commitments; PairingsBn254.G1Point[STATE_WIDTH] permutation_commitments; PairingsBn254.Fr[STATE_WIDTH-1] permutation_non_residues; PairingsBn254.G2Point g2_x; } struct Proof { uint256[] input_values; PairingsBn254.G1Point[STATE_WIDTH] wire_commitments; PairingsBn254.G1Point grand_product_commitment; PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments; PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z; PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega; PairingsBn254.Fr grand_product_at_z_omega; PairingsBn254.Fr quotient_polynomial_at_z; PairingsBn254.Fr linearization_polynomial_at_z; PairingsBn254.Fr[STATE_WIDTH-1] permutation_polynomials_at_z; PairingsBn254.G1Point opening_at_z_proof; PairingsBn254.G1Point opening_at_z_omega_proof; } struct PartialVerifierState { PairingsBn254.Fr alpha; PairingsBn254.Fr beta; PairingsBn254.Fr gamma; PairingsBn254.Fr v; PairingsBn254.Fr u; PairingsBn254.Fr z; PairingsBn254.Fr[] cached_lagrange_evals; } function evaluate_lagrange_poly_out_of_domain( uint256 poly_num, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { require(poly_num < domain_size); PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory omega_power = omega.pow(poly_num); res = at.pow(domain_size); res.sub_assign(one); require(res.value != 0); // Vanishing polynomial can not be zero at point `at` res.mul_assign(omega_power); PairingsBn254.Fr memory den = PairingsBn254.copy(at); den.sub_assign(omega_power); den.mul_assign(PairingsBn254.new_fr(domain_size)); den = den.inverse(); res.mul_assign(den); } function evaluate_vanishing( uint256 domain_size, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { res = at.pow(domain_size); res.sub_assign(PairingsBn254.new_fr(1)); } function verify_at_z( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z); require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain lhs.mul_assign(proof.quotient_polynomial_at_z); PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z); // public inputs PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0); for (uint256 i = 0; i < proof.input_values.length; i++) { tmp.assign(state.cached_lagrange_evals[i]); tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i])); rhs.add_assign(tmp); } quotient_challenge.mul_assign(state.alpha); PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp.assign(proof.permutation_polynomials_at_z[i]); tmp.mul_assign(state.beta); tmp.add_assign(state.gamma); tmp.add_assign(proof.wire_values_at_z[i]); z_part.mul_assign(tmp); } tmp.assign(state.gamma); // we need a wire value of the last polynomial in enumeration tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]); z_part.mul_assign(tmp); z_part.mul_assign(quotient_challenge); rhs.sub_assign(z_part); quotient_challenge.mul_assign(state.alpha); tmp.assign(state.cached_lagrange_evals[0]); tmp.mul_assign(quotient_challenge); rhs.sub_assign(tmp); return lhs.value == rhs.value; } function reconstruct_d( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point memory res) { // we compute what power of v is used as a delinearization factor in batch opening of // commitments. Let's label W(x) = 1 / (x - z) * // [ // t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z) // + v (r(x) - r(z)) // + v^{2..5} * (witness(x) - witness(z)) // + v^(6..8) * (permutation(x) - permutation(z)) // ] // W'(x) = 1 / (x - z*omega) * // [ // + v^9 (z(x) - z(z*omega)) <- we need this power // + v^10 * (d(x) - d(z*omega)) // ] // // we pay a little for a few arithmetic operations to not introduce another constant uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH + STATE_WIDTH - 1; res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH + 1]); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0); // addition gates for (uint256 i = 0; i < STATE_WIDTH; i++) { tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]); res.point_add_assign(tmp_g1); } // multiplication gate tmp_fr.assign(proof.wire_values_at_z[0]); tmp_fr.mul_assign(proof.wire_values_at_z[1]); tmp_g1 = vk.selector_commitments[STATE_WIDTH].point_mul(tmp_fr); res.point_add_assign(tmp_g1); // d_next tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]); res.point_add_assign(tmp_g1); // z * non_res * beta + gamma + a PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z); grand_product_part_at_z.mul_assign(state.beta); grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]); grand_product_part_at_z.add_assign(state.gamma); for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) { tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.permutation_non_residues[i]); tmp_fr.mul_assign(state.beta); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i+1]); grand_product_part_at_z.mul_assign(tmp_fr); } grand_product_part_at_z.mul_assign(state.alpha); tmp_fr.assign(state.cached_lagrange_evals[0]); tmp_fr.mul_assign(state.alpha); tmp_fr.mul_assign(state.alpha); grand_product_part_at_z.add_assign(tmp_fr); PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening); grand_product_part_at_z_omega.mul_assign(state.u); PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp_fr.assign(state.beta); tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i]); last_permutation_part_at_z.mul_assign(tmp_fr); } last_permutation_part_at_z.mul_assign(state.beta); last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega); last_permutation_part_at_z.mul_assign(state.alpha); // add to the linearization tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z); tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z)); res.point_add_assign(tmp_g1); res.point_mul_assign(state.v); res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega)); } function verify_commitments( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk); PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1); for (uint i = 1; i < proof.quotient_poly_commitments.length; i++) { tmp_fr.mul_assign(z_in_domain_size); tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); commitment_aggregation.point_add_assign(d); for (uint i = 0; i < proof.wire_commitments.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint i = 0; i < vk.permutation_commitments.length - 1; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); // collect opening values aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.linearization_polynomial_at_z); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); for (uint i = 0; i < proof.wire_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint i = 0; i < proof.permutation_polynomials_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.permutation_polynomials_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.grand_product_at_z_omega); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z_omega[0]); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value)); PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation; pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z)); tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.omega); tmp_fr.mul_assign(state.u); pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr)); PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u); pair_with_x.point_add_assign(proof.opening_at_z_proof); pair_with_x.negate(); return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x); } function verify_initial( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { require(proof.input_values.length == vk.num_inputs); require(vk.num_inputs == 1); TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); for (uint256 i = 0; i < vk.num_inputs; i++) { transcript.update_with_u256(proof.input_values[i]); } for (uint256 i = 0; i < proof.wire_commitments.length; i++) { transcript.update_with_g1(proof.wire_commitments[i]); } state.beta = transcript.get_challenge(); state.gamma = transcript.get_challenge(); transcript.update_with_g1(proof.grand_product_commitment); state.alpha = transcript.get_challenge(); for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) { transcript.update_with_g1(proof.quotient_poly_commitments[i]); } state.z = transcript.get_challenge(); state.cached_lagrange_evals = new PairingsBn254.Fr[](1); state.cached_lagrange_evals[0] = evaluate_lagrange_poly_out_of_domain( 0, vk.domain_size, vk.omega, state.z ); bool valid = verify_at_z(state, proof, vk); if (valid == false) { return false; } for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { transcript.update_with_fr(proof.wire_values_at_z[i]); } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { transcript.update_with_fr(proof.wire_values_at_z_omega[i]); } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { transcript.update_with_fr(proof.permutation_polynomials_at_z[i]); } transcript.update_with_fr(proof.quotient_polynomial_at_z); transcript.update_with_fr(proof.linearization_polynomial_at_z); transcript.update_with_fr(proof.grand_product_at_z_omega); state.v = transcript.get_challenge(); transcript.update_with_g1(proof.opening_at_z_proof); transcript.update_with_g1(proof.opening_at_z_omega_proof); state.u = transcript.get_challenge(); return true; } // This verifier is for a PLONK with a state width 4 // and main gate equation // q_a(X) * a(X) + // q_b(X) * b(X) + // q_c(X) * c(X) + // q_d(X) * d(X) + // q_m(X) * a(X) * b(X) + // q_constants(X)+ // q_d_next(X) * d(X*omega) // where q_{}(X) are selectors a, b, c, d - state (witness) polynomials // q_d_next(X) "peeks" into the next row of the trace, so it takes // the same d(X) polynomial, but shifted function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) { PartialVerifierState memory state; bool valid = verify_initial(state, proof, vk); if (valid == false) { return false; } valid = verify_commitments(state, proof, vk); return valid; } } contract SingleVerifierWithDeserialize is Plonk4SingleVerifierWithAccessToDNext { uint256 constant SERIALIZED_PROOF_LENGTH = 33; function deserialize_proof( uint256[] memory public_inputs, uint256[] memory serialized_proof ) internal pure returns(Proof memory proof) { require(serialized_proof.length == SERIALIZED_PROOF_LENGTH); proof.input_values = new uint256[](public_inputs.length); for (uint256 i = 0; i < public_inputs.length; i++) { proof.input_values[i] = public_inputs[i]; } uint256 j = 0; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; } proof.grand_product_commitment = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; } for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_values_at_z[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } proof.grand_product_at_z_omega = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; proof.quotient_polynomial_at_z = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; proof.linearization_polynomial_at_z = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } proof.opening_at_z_proof = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); } } pragma solidity >=0.5.0; interface IUniswapV2ERC20 { 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); } pragma solidity =0.5.16; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library UniswapSafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } pragma solidity >=0.5.0 <0.7.0; library PairingsBn254 { uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint256 constant bn254_b_coeff = 3; struct G1Point { uint256 X; uint256 Y; } struct Fr { uint256 value; } function new_fr(uint256 fr) internal pure returns (Fr memory) { require(fr < r_mod); return Fr({value: fr}); } function copy(Fr memory self) internal pure returns (Fr memory n) { n.value = self.value; } function assign(Fr memory self, Fr memory other) internal pure { self.value = other.value; } function inverse(Fr memory fr) internal view returns (Fr memory) { require(fr.value != 0); return pow(fr, r_mod-2); } function add_assign(Fr memory self, Fr memory other) internal pure { self.value = addmod(self.value, other.value, r_mod); } function sub_assign(Fr memory self, Fr memory other) internal pure { self.value = addmod(self.value, r_mod - other.value, r_mod); } function mul_assign(Fr memory self, Fr memory other) internal pure { self.value = mulmod(self.value, other.value, r_mod); } function pow(Fr memory self, uint256 power) internal view returns (Fr memory) { uint256[6] memory input = [32, 32, 32, self.value, power, r_mod]; uint256[1] memory result; bool success; assembly { success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20) } require(success); return Fr({value: result[0]}); } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint[2] X; uint[2] Y; } function P1() internal pure returns (G1Point memory) { return G1Point(1, 2); } function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) { return G1Point(x, y); } function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) { if (x == 0 && y == 0) { // point of infinity is (0,0) return G1Point(x, y); } // check encoding require(x < q_mod); require(y < q_mod); // check on curve uint256 lhs = mulmod(y, y, q_mod); // y^2 uint256 rhs = mulmod(x, x, q_mod); // x^2 rhs = mulmod(rhs, x, q_mod); // x^3 rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b require(lhs == rhs); return G1Point(x, y); } function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) { return G2Point(x, y); } function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) { result.X = self.X; result.Y = self.Y; } function P2() internal pure returns (G2Point memory) { // for some reason ethereum expects to have c1*v + c0 form return G2Point( [0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2, 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed], [0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa] ); } function negate(G1Point memory self) internal pure { // The prime q in the base field F_q for G1 if (self.Y == 0) { require(self.X == 0); return; } self.Y = q_mod - self.Y; } function point_add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) { point_add_into_dest(p1, p2, r); return r; } function point_add_assign(G1Point memory p1, G1Point memory p2) internal view { point_add_into_dest(p1, p2, p1); } function point_add_into_dest(G1Point memory p1, G1Point memory p2, G1Point memory dest) internal view { if (p2.X == 0 && p2.Y == 0) { // we add zero, nothing happens dest.X = p1.X; dest.Y = p1.Y; return; } else if (p1.X == 0 && p1.Y == 0) { // we add into zero, and we add non-zero point dest.X = p2.X; dest.Y = p2.Y; return; } else { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success = false; assembly { success := staticcall(gas(), 6, input, 0x80, dest, 0x40) } require(success); } } function point_sub_assign(G1Point memory p1, G1Point memory p2) internal view { point_sub_into_dest(p1, p2, p1); } function point_sub_into_dest(G1Point memory p1, G1Point memory p2, G1Point memory dest) internal view { if (p2.X == 0 && p2.Y == 0) { // we subtracted zero, nothing happens dest.X = p1.X; dest.Y = p1.Y; return; } else if (p1.X == 0 && p1.Y == 0) { // we subtract from zero, and we subtract non-zero point dest.X = p2.X; dest.Y = q_mod - p2.Y; return; } else { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = q_mod - p2.Y; bool success = false; assembly { success := staticcall(gas(), 6, input, 0x80, dest, 0x40) } require(success); } } function point_mul(G1Point memory p, Fr memory s) internal view returns (G1Point memory r) { point_mul_into_dest(p, s, r); return r; } function point_mul_assign(G1Point memory p, Fr memory s) internal view { point_mul_into_dest(p, s, p); } function point_mul_into_dest(G1Point memory p, Fr memory s, G1Point memory dest) internal view { uint[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s.value; bool success; assembly { success := staticcall(gas(), 7, input, 0x60, dest, 0x40) } require(success); } function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) { require(p1.length == p2.length); uint elements = p1.length; uint inputSize = elements * 6; uint[] memory input = new uint[](inputSize); for (uint i = 0; i < elements; i++) { input[i * 6 + 0] = p1[i].X; input[i * 6 + 1] = p1[i].Y; input[i * 6 + 2] = p2[i].X[0]; input[i * 6 + 3] = p2[i].X[1]; input[i * 6 + 4] = p2[i].Y[0]; input[i * 6 + 5] = p2[i].Y[1]; } uint[1] memory out; bool success; assembly { success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) } require(success); return out[0] != 0; } /// Convenience method for a pairing check for two pairs. function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; p1[1] = b1; p2[0] = a2; p2[1] = b2; return pairing(p1, p2); } } library TranscriptLibrary { // flip 0xe000000000000000000000000000000000000000000000000000000000000000; uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint32 constant DST_0 = 0; uint32 constant DST_1 = 1; uint32 constant DST_CHALLENGE = 2; struct Transcript { bytes32 state_0; bytes32 state_1; uint32 challenge_counter; } function new_transcript() internal pure returns (Transcript memory t) { t.state_0 = bytes32(0); t.state_1 = bytes32(0); t.challenge_counter = 0; } function update_with_u256(Transcript memory self, uint256 value) internal pure { bytes32 old_state_0 = self.state_0; self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value)); self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value)); } function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure { update_with_u256(self, value.value); } function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure { update_with_u256(self, p.X); update_with_u256(self, p.Y); } function get_challenge(Transcript memory self) internal pure returns(PairingsBn254.Fr memory challenge) { bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter)); self.challenge_counter += 1; challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK}); } }
we compute what power of v is used as a delinearization factor in batch opening of commitments. Let's label W(x) = 1 / (x - z) [ t_0(x) + z^n t_1(x) + z^2n t_2(x) + z^3n t_3(x) - t(z) + v (r(x) - r(z)) + v^{2..5} (witness(x) - witness(z)) + v^(6..8) (permutation(x) - permutation(z)) ] W'(x) = 1 / (x - zomega) [ + v^9 (z(x) - z(zomega)) <- we need this power + v^10 (d(x) - d(zomega)) ] we pay a little for a few arithmetic operations to not introduce another constant addition gates
function reconstruct_d( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point memory res) { uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH + STATE_WIDTH - 1; res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH + 1]); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0); for (uint256 i = 0; i < STATE_WIDTH; i++) { tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]); res.point_add_assign(tmp_g1); } tmp_fr.mul_assign(proof.wire_values_at_z[1]); tmp_g1 = vk.selector_commitments[STATE_WIDTH].point_mul(tmp_fr); res.point_add_assign(tmp_g1); res.point_add_assign(tmp_g1); grand_product_part_at_z.mul_assign(state.beta); grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]); grand_product_part_at_z.add_assign(state.gamma); for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) { tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.permutation_non_residues[i]); tmp_fr.mul_assign(state.beta); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i+1]); grand_product_part_at_z.mul_assign(tmp_fr); } grand_product_part_at_z.mul_assign(state.alpha); tmp_fr.assign(state.cached_lagrange_evals[0]); tmp_fr.mul_assign(state.alpha); tmp_fr.mul_assign(state.alpha); grand_product_part_at_z.add_assign(tmp_fr); PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening); grand_product_part_at_z_omega.mul_assign(state.u); PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp_fr.assign(state.beta); tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i]); last_permutation_part_at_z.mul_assign(tmp_fr); } last_permutation_part_at_z.mul_assign(state.beta); last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega); last_permutation_part_at_z.mul_assign(state.alpha); tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z)); res.point_add_assign(tmp_g1); res.point_mul_assign(state.v); res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega)); }
1,250,621
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./StakingPoolManager.sol"; import "./StakingPool.sol"; /// @dev reader contract to easily fetch all relevant info for an account contract View { struct Data { uint256 pendingRewards; Pool[] pools; Pool escrowPool; uint256 totalWeight; } struct Deposit { uint256 amount; uint64 start; uint64 end; uint256 multiplier; } struct Pool { address poolAddress; uint256 totalPoolShares; address depositToken; uint256 accountPendingRewards; uint256 accountClaimedRewards; uint256 accountTotalDeposit; uint256 accountPoolShares; uint256 weight; Deposit[] deposits; } StakingPoolManager public immutable stakingPoolManager; StakingPool public immutable escrowPool; constructor(address _stakingPoolManager, address _escrowPool) { stakingPoolManager = StakingPoolManager(_stakingPoolManager); escrowPool = StakingPool(_escrowPool); } function fetchData(address _account) external view returns (Data memory result) { uint256 rewardPerBlock = stakingPoolManager.rewardPerBlock(); uint256 rewardEndBlock = stakingPoolManager.rewardEndBlock(); uint256 lastRewardBlock = stakingPoolManager.lastRewardBlock(); uint256 pendingRewards = rewardPerBlock * stakingPoolManager.getMultiplier(lastRewardBlock, block.number, rewardEndBlock); result.pendingRewards = pendingRewards; result.totalWeight = stakingPoolManager.totalWeight(); StakingPoolManager.Pool[] memory pools = stakingPoolManager.getPools(); result.pools = new Pool[](pools.length); for (uint256 i = 0; i < pools.length; i++) { StakingPool poolContract = StakingPool(address(pools[i].poolContract)); uint256 depositsOfLength = poolContract.getDepositsOfLength(_account); result.pools[i] = Pool({ poolAddress: address(pools[i].poolContract), totalPoolShares: poolContract.totalSupply(), depositToken: address(poolContract.depositToken()), accountPendingRewards: poolContract.withdrawableRewardsOf(_account), accountClaimedRewards: poolContract.withdrawnRewardsOf(_account), accountTotalDeposit: poolContract.totalDepositOf(_account), accountPoolShares: poolContract.balanceOf(_account), weight: pools[i].weight, deposits: new Deposit[](depositsOfLength) }); StakingPool.Deposit[] memory poolDeposits = poolContract.getDepositsOf(_account, 0, depositsOfLength); for (uint256 j = 0; j < result.pools[i].deposits.length; j++) { StakingPool.Deposit memory deposit = poolDeposits[j]; result.pools[i].deposits[j] = Deposit({ amount: deposit.amount, start: deposit.start, end: deposit.end, multiplier: poolContract.getMultiplier(deposit.end - deposit.start) }); } } result.escrowPool = Pool({ poolAddress: address(escrowPool), totalPoolShares: escrowPool.totalSupply(), depositToken: address(escrowPool.depositToken()), accountPendingRewards: escrowPool.withdrawableRewardsOf(_account), accountClaimedRewards: escrowPool.withdrawnRewardsOf(_account), accountTotalDeposit: escrowPool.totalDepositOf(_account), accountPoolShares: escrowPool.balanceOf(_account), weight: 0, deposits: new Deposit[](escrowPool.getDepositsOfLength(_account)) }); StakingPool.Deposit[] memory escrowDeposits = escrowPool.getDepositsOf( _account, 0, escrowPool.getDepositsOfLength(_account) ); for (uint256 j = 0; j < result.escrowPool.deposits.length; j++) { StakingPool.Deposit memory deposit = escrowDeposits[j]; result.escrowPool.deposits[j] = Deposit({ amount: deposit.amount, start: deposit.start, end: deposit.end, multiplier: escrowPool.getMultiplier(deposit.end - deposit.start) }); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IBasePool.sol"; import "./base/TokenSaver.sol"; contract StakingPoolManager is TokenSaver { using SafeERC20 for IERC20; bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE"); bytes32 public constant REWARD_DISTRIBUTOR_ROLE = keccak256("REWARD_DISTRIBUTOR_ROLE"); uint256 public constant MAX_POOL_COUNT = 10; IERC20 public immutable reward; address public immutable rewardSource; /// @dev RewardPerBlock uint256 public rewardPerBlock; /// @dev When rewards were last paid uint256 public lastRewardBlock; /// @dev Reward end block uint256 public rewardEndBlock; uint256 public totalWeight; mapping(address => bool) public poolAdded; Pool[] public pools; struct Pool { IBasePool poolContract; uint256 weight; } modifier onlyGov() { require(hasRole(GOV_ROLE, _msgSender()), "only gov"); _; } modifier onlyRewardDistributor() { require(hasRole(REWARD_DISTRIBUTOR_ROLE, _msgSender()), "only reward dist"); _; } event PoolAdded(address indexed pool, uint256 weight); event PoolRemoved(uint256 indexed poolId, address indexed pool); event WeightAdjusted(uint256 indexed poolId, address indexed pool, uint256 newWeight); event SetRewardsPerBlock(uint256 rewardsPerBlock); event SetRewardEndBlock(uint256 rewardEndBlock); event RewardsDistributed(address _from, uint256 indexed _amount); constructor( address _reward, address _rewardSource, uint256 _rewardStartBlock, uint256 _rewardEndBlock ) { require(_reward != address(0), "bad _reward"); require(_rewardSource != address(0), "bad _rewardSource"); require(_rewardStartBlock > block.number && _rewardStartBlock < _rewardEndBlock, "bad _rewardStartBlock"); reward = IERC20(_reward); rewardSource = _rewardSource; lastRewardBlock = _rewardStartBlock; rewardEndBlock = _rewardEndBlock; } function addPool(address _poolContract, uint256 _weight) external onlyGov { _distributeRewards(); require(_poolContract != address(0), "bad _poolContract"); require(!poolAdded[_poolContract], "pool already added"); require(pools.length < MAX_POOL_COUNT, "max amount of pools reached"); // add pool pools.push(Pool({ poolContract: IBasePool(_poolContract), weight: _weight })); poolAdded[_poolContract] = true; // increase totalWeight totalWeight += _weight; // Approve max token amount reward.safeApprove(_poolContract, type(uint256).max); emit PoolAdded(_poolContract, _weight); } function removePool(uint256 _poolId) external onlyGov { require(_poolId < pools.length, "!exist"); _distributeRewards(); address poolAddress = address(pools[_poolId].poolContract); // decrease totalWeight totalWeight -= pools[_poolId].weight; // remove pool pools[_poolId] = pools[pools.length - 1]; pools.pop(); poolAdded[poolAddress] = false; emit PoolRemoved(_poolId, poolAddress); } function adjustWeight(uint256 _poolId, uint256 _newWeight) external onlyGov { require(_poolId < pools.length, "!exist"); _distributeRewards(); Pool storage pool = pools[_poolId]; totalWeight -= pool.weight; totalWeight += _newWeight; pool.weight = _newWeight; emit WeightAdjusted(_poolId, address(pool.poolContract), _newWeight); } function setRewardEndBlock(uint256 _rewardEndBlock) external onlyGov { require(_rewardEndBlock > rewardEndBlock, "!future"); rewardEndBlock = _rewardEndBlock; emit SetRewardEndBlock(rewardPerBlock); } function setRewardPerBlock(uint256 _rewardPerBlock) external onlyGov { _distributeRewards(); rewardPerBlock = _rewardPerBlock; emit SetRewardsPerBlock(_rewardPerBlock); } /// @notice Return reward multiplier over the given _from to _to block. function getMultiplier( uint256 _from, uint256 _to, uint256 _endBlock ) public pure returns (uint256) { if ((_from >= _endBlock) || (_from > _to)) { return 0; } if (_to <= _endBlock) { return _to - _from; } return _endBlock - _from; } function _distributeRewards() internal { uint256 blockPassed = getMultiplier(lastRewardBlock, block.number, rewardEndBlock); if (blockPassed == 0) { return; } uint256 totalRewardAmount = rewardPerBlock * blockPassed; lastRewardBlock = block.number >= rewardEndBlock ? rewardEndBlock : block.number; // return if pool length == 0 if (pools.length == 0) { return; } // return if accrued rewards == 0 if (totalRewardAmount == 0) { return; } reward.safeTransferFrom(rewardSource, address(this), totalRewardAmount); for (uint256 i = 0; i < pools.length; i++) { Pool memory pool = pools[i]; uint256 poolRewardAmount = (totalRewardAmount * pool.weight) / totalWeight; // Ignore tx failing to prevent a single pool from halting reward distribution // solhint-disable-next-line address(pool.poolContract).call( abi.encodeWithSelector(pool.poolContract.distributeRewards.selector, poolRewardAmount) ); } uint256 leftOverReward = reward.balanceOf(address(this)); // send back excess but ignore dust if (leftOverReward > 1) { reward.safeTransfer(rewardSource, leftOverReward); } emit RewardsDistributed(_msgSender(), totalRewardAmount); } function distributeRewards() external onlyRewardDistributor { _distributeRewards(); } function getPools() external view returns (Pool[] memory result) { return pools; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./base/BasePool.sol"; import "./interfaces/ITimeLockPool.sol"; contract StakingPool is BasePool, ITimeLockPool { using Math for uint256; using SafeERC20 for IERC20; uint256 public immutable maxBonus; uint256 public immutable maxLockDuration; uint256 public constant MIN_LOCK_DURATION = 2 weeks; mapping(address => Deposit[]) public depositsOf; mapping(address => uint256) public totalDepositOf; struct Deposit { uint256 amount; uint64 start; uint64 end; } constructor( string memory _name, string memory _symbol, address _depositToken, address _rewardToken, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration, uint256 _maxBonus, uint256 _maxLockDuration ) BasePool(_name, _symbol, _depositToken, _rewardToken, _escrowPool, _escrowPortion, _escrowDuration) { require(_maxLockDuration >= MIN_LOCK_DURATION, "bad _maxLockDuration"); maxBonus = _maxBonus; maxLockDuration = _maxLockDuration; } event Deposited(uint256 amount, uint256 duration, address indexed receiver, address indexed from); event Withdrawn(uint256 indexed depositId, address indexed receiver, address indexed from, uint256 amount); function deposit( uint256 _amount, uint256 _duration, address _receiver ) external override { require(_amount > 0, "bad _amount"); // Don't allow locking > maxLockDuration uint256 duration = _duration.min(maxLockDuration); // Enforce min lockup duration to prevent flash loan or MEV transaction ordering duration = duration.max(MIN_LOCK_DURATION); depositToken.safeTransferFrom(_msgSender(), address(this), _amount); depositsOf[_receiver].push( Deposit({ amount: _amount, start: uint64(block.timestamp), end: uint64(block.timestamp) + uint64(duration) }) ); totalDepositOf[_receiver] += _amount; uint256 mintAmount = (_amount * getMultiplier(duration)) / 1e18; _mint(_receiver, mintAmount); emit Deposited(_amount, duration, _receiver, _msgSender()); } function getMultiplier(uint256 _lockDuration) public view returns (uint256) { return 1e18 + ((maxBonus * _lockDuration) / maxLockDuration); } function getDepositsOf( address _account, uint256 skip, uint256 limit ) public view returns (Deposit[] memory) { Deposit[] memory _depositsOf = new Deposit[](limit); uint256 depositsOfLength = depositsOf[_account].length; if (skip >= depositsOfLength) return _depositsOf; for (uint256 i = skip; i < (skip + limit).min(depositsOfLength); i++) { _depositsOf[i - skip] = depositsOf[_account][i]; } return _depositsOf; } function getDepositsOfLength(address _account) public view returns (uint256) { return depositsOf[_account].length; } /// @notice Disable share transfers function _transfer( address, /* _from */ address, /* _to */ uint256 /* _amount */ ) internal pure override { revert("non-transferable"); } function withdraw(uint256 _depositId, address _receiver) external { require(_depositId < depositsOf[_msgSender()].length, "!exist"); Deposit memory userDeposit = depositsOf[_msgSender()][_depositId]; require(block.timestamp >= userDeposit.end, "too soon"); // No risk of wrapping around on casting to uint256 since deposit end always > deposit start and types are 64 bits uint256 shareAmount = (userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start))) / 1e18; // remove Deposit totalDepositOf[_msgSender()] -= userDeposit.amount; depositsOf[_msgSender()][_depositId] = depositsOf[_msgSender()][depositsOf[_msgSender()].length - 1]; depositsOf[_msgSender()].pop(); // burn pool shares _burn(_msgSender(), shareAmount); // return tokens depositToken.safeTransfer(_receiver, userDeposit.amount); emit Withdrawn(_depositId, _receiver, _msgSender(), userDeposit.amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) 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.10; interface IBasePool { function distributeRewards(uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; contract TokenSaver is AccessControlEnumerable { using SafeERC20 for IERC20; bytes32 public constant TOKEN_SAVER_ROLE = keccak256("TOKEN_SAVER_ROLE"); event TokenSaved(address indexed by, address indexed receiver, address indexed token, uint256 amount); modifier onlyTokenSaver() { require(hasRole(TOKEN_SAVER_ROLE, _msgSender()), "only token saver"); _; } constructor() { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function saveToken( address _token, address _receiver, uint256 _amount ) external onlyTokenSaver { IERC20(_token).safeTransfer(_receiver, _amount); emit TokenSaved(_msgSender(), _receiver, _token, _amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view 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) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _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()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (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.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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "../interfaces/IBasePool.sol"; import "../interfaces/ITimeLockPool.sol"; import "./AbstractRewards.sol"; import "./TokenSaver.sol"; abstract contract BasePool is ERC20Votes, AbstractRewards, IBasePool { using SafeERC20 for IERC20; using SafeCast for uint256; using SafeCast for int256; IERC20 public immutable depositToken; IERC20 public immutable rewardToken; ITimeLockPool public immutable escrowPool; uint256 public immutable escrowPortion; // how much is escrowed 1e18 == 100% uint256 public immutable escrowDuration; // escrow duration in seconds event RewardsClaimed( address indexed _from, address indexed _receiver, uint256 _escrowedAmount, uint256 _nonEscrowedAmount ); constructor( string memory _name, string memory _symbol, address _depositToken, address _rewardToken, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration ) ERC20Permit(_name) ERC20(_name, _symbol) AbstractRewards(balanceOf, totalSupply) { require(_escrowPortion <= 1e18, "BasePool.constructor: Cannot escrow more than 100%"); require(_depositToken != address(0), "BasePool.constructor: Deposit token must be set"); depositToken = IERC20(_depositToken); rewardToken = IERC20(_rewardToken); escrowPool = ITimeLockPool(_escrowPool); escrowPortion = _escrowPortion; escrowDuration = _escrowDuration; if (_rewardToken != address(0) && _escrowPool != address(0)) { IERC20(_rewardToken).safeApprove(_escrowPool, type(uint256).max); } } function _mint(address _account, uint256 _amount) internal virtual override { super._mint(_account, _amount); _correctPoints(_account, -(_amount.toInt256())); } function _burn(address _account, uint256 _amount) internal virtual override { super._burn(_account, _amount); _correctPoints(_account, _amount.toInt256()); } function _transfer( address _from, address _to, uint256 _value ) internal virtual override { super._transfer(_from, _to, _value); _correctPointsForTransfer(_from, _to, _value); } function distributeRewards(uint256 _amount) external override { rewardToken.safeTransferFrom(_msgSender(), address(this), _amount); _distributeRewards(_amount); } function claimRewards(address _receiver) external virtual { uint256 rewardAmount = _prepareCollect(_msgSender()); uint256 escrowedRewardAmount = (rewardAmount * escrowPortion) / 1e18; uint256 nonEscrowedRewardAmount = rewardAmount - escrowedRewardAmount; if (escrowedRewardAmount != 0 && address(escrowPool) != address(0)) { escrowPool.deposit(escrowedRewardAmount, escrowDuration, _receiver); } // ignore dust if (nonEscrowedRewardAmount > 1) { rewardToken.safeTransfer(_receiver, nonEscrowedRewardAmount); } emit RewardsClaimed(_msgSender(), _receiver, escrowedRewardAmount, nonEscrowedRewardAmount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface ITimeLockPool { function deposit( uint256 _amount, uint256 _duration, address _receiver ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/ERC20Votes.sol) pragma solidity ^0.8.0; import "./draft-ERC20Permit.sol"; import "../../../utils/math/Math.sol"; import "../../../utils/math/SafeCast.sol"; import "../../../utils/cryptography/ECDSA.sol"; /** * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. * * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this * will significantly increase the base gas cost of transfers. * * _Available since v4.2._ */ abstract contract ERC20Votes is ERC20Permit { struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual { _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); _delegate(signer, delegatee); } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)})); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/SafeCast.sol) pragma solidity ^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 uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @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 <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "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 <= type(uint32).max, "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 <= type(uint16).max, "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 <= type(uint8).max, "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 >= type(int128).min && value <= type(int128).max, "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 >= type(int64).min && value <= type(int64).max, "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 >= type(int32).min && value <= type(int32).max, "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 >= type(int16).min && value <= type(int16).max, "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 >= type(int8).min && value <= type(int8).max, "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) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "../interfaces/IAbstractRewards.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; /** * @dev Based on: https://github.com/indexed-finance/dividends/blob/master/contracts/base/AbstractDividends.sol * Renamed dividends to rewards. * @dev (OLD) Many functions in this contract were taken from this repository: * https://github.com/atpar/funds-distribution-token/blob/master/contracts/FundsDistributionToken.sol * which is an example implementation of ERC 2222, the draft for which can be found at * https://github.com/atpar/funds-distribution-token/blob/master/EIP-DRAFT.md * * This contract has been substantially modified from the original and does not comply with ERC 2222. * Many functions were renamed as "rewards" rather than "funds" and the core functionality was separated * into this abstract contract which can be inherited by anything tracking ownership of reward shares. */ abstract contract AbstractRewards is IAbstractRewards { using SafeCast for uint128; using SafeCast for uint256; using SafeCast for int256; /* ======== Constants ======== */ uint128 public constant POINTS_MULTIPLIER = type(uint128).max; /* ======== Internal Function References ======== */ function(address) view returns (uint256) private immutable getSharesOf; function() view returns (uint256) private immutable getTotalShares; /* ======== Storage ======== */ uint256 public pointsPerShare; mapping(address => int256) public pointsCorrection; mapping(address => uint256) public withdrawnRewards; constructor(function(address) view returns (uint256) getSharesOf_, function() view returns (uint256) getTotalShares_) { getSharesOf = getSharesOf_; getTotalShares = getTotalShares_; } /* ======== Public View Functions ======== */ /** * @dev Returns the total amount of rewards a given address is able to withdraw. * @param _account Address of a reward recipient * @return A uint256 representing the rewards `account` can withdraw */ function withdrawableRewardsOf(address _account) public view override returns (uint256) { return cumulativeRewardsOf(_account) - withdrawnRewards[_account]; } /** * @notice View the amount of rewards that an address has withdrawn. * @param _account The address of a token holder. * @return The amount of rewards that `account` has withdrawn. */ function withdrawnRewardsOf(address _account) public view override returns (uint256) { return withdrawnRewards[_account]; } /** * @notice View the amount of rewards that an address has earned in total. * @dev accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account) * = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER * @param _account The address of a token holder. * @return The amount of rewards that `account` has earned in total. */ function cumulativeRewardsOf(address _account) public view override returns (uint256) { return ((pointsPerShare * getSharesOf(_account)).toInt256() + pointsCorrection[_account]).toUint256() / POINTS_MULTIPLIER; } /* ======== Dividend Utility Functions ======== */ /** * @notice Distributes rewards to token holders. * @dev It reverts if the total shares is 0. * It emits the `RewardsDistributed` event if the amount to distribute is greater than 0. * About undistributed rewards: * In each distribution, there is a small amount which does not get distributed, * which is `(amount * POINTS_MULTIPLIER) % totalShares()`. * With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting * distributed in a distribution can be less than 1 (base unit). */ function _distributeRewards(uint256 _amount) internal { uint256 shares = getTotalShares(); require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero"); if (_amount > 0) { pointsPerShare = pointsPerShare + ((_amount * POINTS_MULTIPLIER) / shares); emit RewardsDistributed(msg.sender, _amount); } } /** * @notice Prepares collection of owed rewards * @dev It emits a `RewardsWithdrawn` event if the amount of withdrawn rewards is * greater than 0. */ function _prepareCollect(address _account) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableRewardsOf(_account); if (_withdrawableDividend > 0) { withdrawnRewards[_account] = withdrawnRewards[_account] + _withdrawableDividend; emit RewardsWithdrawn(_account, _withdrawableDividend); } return _withdrawableDividend; } function _correctPointsForTransfer( address _from, address _to, uint256 _shares ) internal { int256 _magCorrection = (pointsPerShare * _shares).toInt256(); pointsCorrection[_from] = pointsCorrection[_from] + _magCorrection; pointsCorrection[_to] = pointsCorrection[_to] - _magCorrection; } /** * @dev Increases or decreases the points correction for `account` by * `shares*pointsPerShare`. */ function _correctPoints(address _account, int256 _shares) internal { pointsCorrection[_account] = pointsCorrection[_account] + (_shares * (int256(pointsPerShare))); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IAbstractRewards { /** * @dev Returns the total amount of rewards a given address is able to withdraw. * @param account Address of a reward recipient * @return A uint256 representing the rewards `account` can withdraw */ function withdrawableRewardsOf(address account) external view returns (uint256); /** * @dev View the amount of funds that an address has withdrawn. * @param account The address of a token holder. * @return The amount of funds that `account` has withdrawn. */ function withdrawnRewardsOf(address account) external view returns (uint256); /** * @dev View the amount of funds that an address has earned in total. * accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account) * = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER * @param account The address of a token holder. * @return The amount of funds that `account` has earned in total. */ function cumulativeRewardsOf(address account) external view returns (uint256); /** * @dev This event emits when new funds are distributed * @param by the address of the sender who distributed funds * @param rewardsDistributed the amount of funds received for distribution */ event RewardsDistributed(address indexed by, uint256 rewardsDistributed); /** * @dev This event emits when distributed funds are withdrawn by a token holder. * @param by the address of the receiver of funds * @param fundsWithdrawn the amount of funds that were withdrawn */ event RewardsWithdrawn(address indexed by, uint256 fundsWithdrawn); }
return if pool length == 0 return if accrued rewards == 0 Ignore tx failing to prevent a single pool from halting reward distribution solhint-disable-next-line send back excess but ignore dust
function _distributeRewards() internal { uint256 blockPassed = getMultiplier(lastRewardBlock, block.number, rewardEndBlock); if (blockPassed == 0) { return; } uint256 totalRewardAmount = rewardPerBlock * blockPassed; lastRewardBlock = block.number >= rewardEndBlock ? rewardEndBlock : block.number; if (pools.length == 0) { return; } if (totalRewardAmount == 0) { return; } reward.safeTransferFrom(rewardSource, address(this), totalRewardAmount); for (uint256 i = 0; i < pools.length; i++) { Pool memory pool = pools[i]; uint256 poolRewardAmount = (totalRewardAmount * pool.weight) / totalWeight; address(pool.poolContract).call( abi.encodeWithSelector(pool.poolContract.distributeRewards.selector, poolRewardAmount) ); } uint256 leftOverReward = reward.balanceOf(address(this)); if (leftOverReward > 1) { reward.safeTransfer(rewardSource, leftOverReward); } emit RewardsDistributed(_msgSender(), totalRewardAmount); }
11,801,387
/** *Submitted for verification at Etherscan.io on 2022-03-17 */ // SPDX-License-Identifier: MIT 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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface ISwapFactory { function balanceCallback(address hashAddress, uint256 foreignBalance) external returns(bool); function balancesCallback( address hashAddress, uint256 foreignBalance, // total user's tokens balance on foreign chain uint256 foreignSpent, // total tokens spent by SmartSwap pair uint256 nativeEncoded // (nativeSpent, nativeRate) = _decode(nativeEncoded) ) external returns(bool); } // 1 - BNB, 2 - ETH, 3 - BTC, 4 - MATIC interface ICompanyOracle { function getBalance(uint256 network,address token,address user) external returns(uint256); function getPriceAndBalance(address tokenA,address tokenB,uint256 network,address token,address[] calldata user) external returns(uint256); } interface IPriceFeed { function latestAnswer() external returns (int256); } contract Validator is Ownable { uint256 constant NETWORK = 137; // ETH mainnet = 1, Ropsten = 3,Kovan - 42, BSC_TESTNET = 97, BSC_MAINNET = 56, MATIC = 137 uint256 constant NOMINATOR = 10**18; // rate nominator mapping(address => bool) public isAllowedAddress; address public factory; address public companyOracle; mapping (uint256 => address) public companyOracleRequests; // companyOracleRequest ID => user (hashAddress) mapping (uint256 => uint256) public gasLimit; // request type => amount of gas uint256 public customGasPrice = 50 * 10**9; // 20 GWei mapping(address => IPriceFeed) tokenPriceFeed; event LogMsg(string description); modifier onlyAllowed() { require(isAllowedAddress[msg.sender] || owner() == msg.sender,"ERR_ALLOWED_ADDRESS_ONLY"); _; } constructor (address _oracle) { companyOracle = _oracle; //Kovan Testnet //tokenPriceFeed[address(1)] = IPriceFeed(0x8993ED705cdf5e84D0a3B754b5Ee0e1783fcdF16); // BNB/USD //tokenPriceFeed[address(2)] = IPriceFeed(0x9326BFA02ADD2366b30bacB125260Af641031331); // ETH/USD // BSC Testnet //tokenPriceFeed[address(1)] = IPriceFeed(0x2514895c72f50D8bd4B4F9b1110F0D6bD2c97526); // BNB/USD //tokenPriceFeed[address(2)] = IPriceFeed(0x143db3CEEfbdfe5631aDD3E50f7614B6ba708BA7); // ETH/USD // ETH mainnet tokenPriceFeed[address(1)] = IPriceFeed(0x14e613AC84a31f709eadbdF89C6CC390fDc9540A); // BNB/USD tokenPriceFeed[address(2)] = IPriceFeed(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); // ETH/USD tokenPriceFeed[address(4)] = IPriceFeed(0x7bAC85A8a13A4BcD8abb3eB7d6b4d632c5a57676); // MATIC/USD // BSC mainnet //tokenPriceFeed[address(1)] = IPriceFeed(0x0567F2323251f0Aab15c8dFb1967E4e8A7D42aeE); // BNB/USD //tokenPriceFeed[address(2)] = IPriceFeed(0x9ef1B8c0E4F7dc8bF5719Ea496883DC6401d5b2e); // ETH/USD //tokenPriceFeed[address(4)] = IPriceFeed(0xAB594600376Ec9fD91F8e885dADF0CE036862dE0); // MATIC/USD } // returns rate (with 9 decimals) = Token B price / Token A price function getRate(address tokenA, address tokenB) external returns (uint256 rate) { int256 priceA = tokenPriceFeed[tokenA].latestAnswer(); int256 priceB = tokenPriceFeed[tokenB].latestAnswer(); require(priceA > 0 && priceB > 0, "Zero price"); rate = uint256(priceB * int256(NOMINATOR) / priceA); // get rate on BSC side: ETH price / BNB price } function setCompanyOracle(address _addr) external onlyOwner returns(bool) { companyOracle = _addr; return true; } function setFactory(address _addr) external onlyOwner returns(bool) { factory = _addr; return true; } function changeAllowedAddress(address _which,bool _bool) external onlyOwner returns(bool){ isAllowedAddress[_which] = _bool; return true; } // returns: oracle fee function getOracleFee(uint256 req) external view returns(uint256) { //req: 1 - cancel, 2 - claim, returns: value return gasLimit[req] * customGasPrice; } function checkBalance(address foreignFactory, address user) external returns(uint256) { require(msg.sender == factory, "Not factory"); uint256 myId = ICompanyOracle(companyOracle).getBalance(NETWORK, foreignFactory, user); companyOracleRequests[myId] = user; return myId; } function oracleCallback(uint256 requestId, uint256 balance) external returns(bool) { require (companyOracle == msg.sender, "Wrong Oracle"); address hashAddress = companyOracleRequests[requestId]; require(hashAddress != address(0), "Wrong requestId"); delete companyOracleRequests[requestId]; // requestId fulfilled ISwapFactory(factory).balanceCallback(hashAddress, balance); return true; } function checkBalances(address foreignFactory, address[] calldata users) external returns(uint256) { require(msg.sender == factory, "Not factory"); uint256 myId = ICompanyOracle(companyOracle).getPriceAndBalance(address(1), address(2), NETWORK, foreignFactory, users); companyOracleRequests[myId] = users[0]; return myId; } function oraclePriceAndBalanceCallback(uint256 requestId,uint256 priceA,uint256 priceB,uint256[] calldata balances) external returns(bool) { require (companyOracle == msg.sender, "Wrong Oracle"); priceA = priceB; // remove unused address hashAddress = companyOracleRequests[requestId]; require(hashAddress != address(0), "Wrong requestId"); delete companyOracleRequests[requestId]; // requestId fulfilled ISwapFactory(factory).balancesCallback(hashAddress, balances[0], balances[1], balances[2]); return true; } function withdraw(uint256 amount) external onlyAllowed returns (bool) { payable(msg.sender).transfer(amount); return true; } // set gas limit to request: 1 - cancel request, 2 - claim request function setGasLimit(uint256 req, uint256 amount) external onlyAllowed returns (bool) { gasLimit[req] = amount; return true; } function setCustomGasPrice(uint256 amount) external onlyAllowed returns (bool) { customGasPrice = amount; //provable_setCustomGasPrice(amount); return true; } receive() external payable {} }
set gas limit to request: 1 - cancel request, 2 - claim request
function setGasLimit(uint256 req, uint256 amount) external onlyAllowed returns (bool) { gasLimit[req] = amount; return true; }
2,125,233
./full_match/1/0xc260732A4eFd258F5EDd60f85d034E59B07fB30C/sources/browser/TriTrade.sol
This function is used when either the _tokenBorrow or _tokenPay is WETH or ETH Since ~all tokens trade against WETH (if they trade at all), we can use a single UniswapV2 pair to flash-borrow and repay with the requested tokens. This initiates the flash borrow. See `simpleFlashSwapExecute` for the code that executes after the borrow.
function simpleFlashSwap( address _pair, address _tokenBorrow, address _tokenPay, uint _amount ) private { address _token0 = IUniswapV2Pair(_pair).token0(); address _token1 = IUniswapV2Pair(_pair).token1(); uint amount0Out = _tokenBorrow == _token0 ? _amount : 0; uint amount1Out = _tokenBorrow == _token1 ? _amount : 0; bytes memory data = abi.encode( _tokenBorrow, _tokenPay, _amount, _pair == pair1, _pair == pair2 ); IUniswapV2Pair(_pair).swap(amount0Out, amount1Out, address(this), data); }
2,916,999
./full_match/122/0x7Fbb9E5aA3E9f813824592fe8AC589E7226704C8/sources/contracts/governance/DelayedClaimableGovernor.sol
Cancels an outstanding governor change request by resetting request time/
function cancelGovernorChange() public override onlyGovernor { requestTime = 0; super.cancelGovernorChange(); }
16,367,337
./partial_match/1/0x2Ad412A1dF96434Eed0779D2dB4A8694a06132f8/sources/src/WorldIDIdentityManagerImplV1.sol
Disables the state bridge. Only the owner of the contract can call this function.
function disableStateBridge() public virtual onlyProxy onlyInitialized onlyOwner { if (_isStateBridgeEnabled) { _isStateBridgeEnabled = false; emit StateBridgeStateChange(false); revert StateBridgeAlreadyDisabled(); } }
4,373,989
./full_match/11155111/0xeB608433549bFd32aB93ceBe18076834Cf1B30F8/sources/contracts/Latest2_HRTCrowdfunding.sol
Create a new campaign campaign.owner = msg.sender;
function createCampaign( address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image, uint256 _minContribution ) public returns (uint256) { Campaign storage campaign = campaigns[numberOfCampaigns]; require(_deadline > block.timestamp, "The deadline should be a date in the future."); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image; campaign.minContribution = _minContribution; numberOfCampaigns++; return numberOfCampaigns - 1; }
3,831,392
// 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"; 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 initialized = false; // epoch uint256 public startTime; uint256 public epoch = 0; uint256 public epochSupplyContractionLeft = 0; // exclusions from total supply address[] public excludedFromTotalSupply = [ address(0xB7e1E341b2CBCc7d1EdF4DC6E5e962aE5C621ca5), // GrapeGenesisRewardPool address(0x04b79c851ed1A36549C6151189c79EC0eaBca745) // GrapeRewardPool ]; // core components address public grape; address public gbond; address public wine; address public boardroom; address public grapeOracle; // price uint256 public grapePriceOne; uint256 public grapePriceCeiling; uint256 public seigniorageSaved; uint256[] public supplyTiers; uint256[] public maxExpansionTiers; uint256 public maxSupplyExpansionPercent; uint256 public bondDepletionFloorPercent; uint256 public seigniorageExpansionFloorPercent; uint256 public maxSupplyContractionPercent; uint256 public maxDebtRatioPercent; // 28 first epochs (1 week) with 4.5% expansion regardless of GRAPE price uint256 public bootstrapEpochs; uint256 public bootstrapSupplyExpansionPercent; /* =================== Added variables =================== */ uint256 public previousEpochGrapePrice; uint256 public maxDiscountRate; // when purchasing bond uint256 public maxPremiumRate; // when redeeming bond uint256 public discountPercent; uint256 public premiumThreshold; uint256 public premiumPercent; uint256 public mintingFactorForPayingDebt; // print extra GRAPE during debt phase address public daoFund; uint256 public daoFundSharedPercent; address public devFund; uint256 public devFundSharedPercent; /* =================== Events =================== */ event Initialized(address indexed executor, uint256 at); event BurnedBonds(address indexed from, uint256 bondAmount); event RedeemedBonds(address indexed from, uint256 grapeAmount, uint256 bondAmount); event BoughtBonds(address indexed from, uint256 grapeAmount, uint256 bondAmount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event DaoFundFunded(uint256 timestamp, uint256 seigniorage); event DevFundFunded(uint256 timestamp, uint256 seigniorage); /* =================== Modifier =================== */ modifier onlyOperator() { require(operator == msg.sender, "Treasury: caller is not the operator"); _; } modifier checkCondition() { require(now >= startTime, "Treasury: not started yet"); _; } modifier checkEpoch() { require(now >= nextEpochPoint(), "Treasury: not opened yet"); _; epoch = epoch.add(1); epochSupplyContractionLeft = (getGrapePrice() > grapePriceCeiling) ? 0 : getGrapeCirculatingSupply().mul(maxSupplyContractionPercent).div(10000); } modifier checkOperator() { require( IBasisAsset(grape).operator() == address(this) && IBasisAsset(gbond).operator() == address(this) && IBasisAsset(wine).operator() == address(this) && Operator(boardroom).operator() == address(this), "Treasury: need more permission" ); _; } modifier notInitialized() { require(!initialized, "Treasury: already initialized"); _; } /* ========== VIEW FUNCTIONS ========== */ function isInitialized() public view returns (bool) { return initialized; } // epoch function nextEpochPoint() public view returns (uint256) { return startTime.add(epoch.mul(PERIOD)); } // oracle function getGrapePrice() public view returns (uint256 grapePrice) { try IOracle(grapeOracle).consult(grape, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("Treasury: failed to consult grape price from the oracle"); } } function getGrapeUpdatedPrice() public view returns (uint256 _grapePrice) { try IOracle(grapeOracle).twap(grape, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("Treasury: failed to consult grape price from the oracle"); } } // budget function getReserve() public view returns (uint256) { return seigniorageSaved; } function getBurnableGrapeLeft() public view returns (uint256 _burnableGrapeLeft) { uint256 _grapePrice = getGrapePrice(); if (_grapePrice <= grapePriceOne) { uint256 _grapeSupply = getGrapeCirculatingSupply(); uint256 _bondMaxSupply = _grapeSupply.mul(maxDebtRatioPercent).div(10000); uint256 _bondSupply = IERC20(gbond).totalSupply(); if (_bondMaxSupply > _bondSupply) { uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply); uint256 _maxBurnableGrape = _maxMintableBond.mul(_grapePrice).div(1e18); _burnableGrapeLeft = Math.min(epochSupplyContractionLeft, _maxBurnableGrape); } } } function getRedeemableBonds() public view returns (uint256 _redeemableBonds) { uint256 _grapePrice = getGrapePrice(); if (_grapePrice > grapePriceCeiling) { uint256 _totalGrape = IERC20(grape).balanceOf(address(this)); uint256 _rate = getBondPremiumRate(); if (_rate > 0) { _redeemableBonds = _totalGrape.mul(1e18).div(_rate); } } } function getBondDiscountRate() public view returns (uint256 _rate) { uint256 _grapePrice = getGrapePrice(); if (_grapePrice <= grapePriceOne) { if (discountPercent == 0) { // no discount _rate = grapePriceOne; } else { uint256 _bondAmount = grapePriceOne.mul(1e18).div(_grapePrice); // to burn 1 GRAPE uint256 _discountAmount = _bondAmount.sub(grapePriceOne).mul(discountPercent).div(10000); _rate = grapePriceOne.add(_discountAmount); if (maxDiscountRate > 0 && _rate > maxDiscountRate) { _rate = maxDiscountRate; } } } } function getBondPremiumRate() public view returns (uint256 _rate) { uint256 _grapePrice = getGrapePrice(); if (_grapePrice > grapePriceCeiling) { uint256 _grapePricePremiumThreshold = grapePriceOne.mul(premiumThreshold).div(100); if (_grapePrice >= _grapePricePremiumThreshold) { //Price > 1.10 uint256 _premiumAmount = _grapePrice.sub(grapePriceOne).mul(premiumPercent).div(10000); _rate = grapePriceOne.add(_premiumAmount); if (maxPremiumRate > 0 && _rate > maxPremiumRate) { _rate = maxPremiumRate; } } else { // no premium bonus _rate = grapePriceOne; } } } /* ========== GOVERNANCE ========== */ function initialize( address _grape, address _gbond, address _wine, address _grapeOracle, address _boardroom, uint256 _startTime ) public notInitialized { grape = _grape; gbond = _gbond; wine = _wine; grapeOracle = _grapeOracle; boardroom = _boardroom; startTime = _startTime; grapePriceOne = 10**18; // This is to allow a PEG of 1 GRAPE per MIM grapePriceCeiling = grapePriceOne.mul(101).div(100); // Dynamic max expansion percent supplyTiers = [0 ether, 10000 ether, 20000 ether, 30000 ether, 40000 ether, 50000 ether, 100000 ether, 200000 ether, 500000 ether]; maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100]; maxSupplyExpansionPercent = 400; // Upto 4.0% supply for expansion bondDepletionFloorPercent = 10000; // 100% of Bond supply for depletion floor seigniorageExpansionFloorPercent = 3500; // At least 35% of expansion reserved for boardroom maxSupplyContractionPercent = 300; // Upto 3.0% supply for contraction (to burn GRAPE and mint GBOND) maxDebtRatioPercent = 4000; // Upto 40% supply of GBOND to purchase premiumThreshold = 110; premiumPercent = 7000; // First 14 epochs with 4.5% expansion bootstrapEpochs = 14; bootstrapSupplyExpansionPercent = 450; // set seigniorageSaved to it's balance seigniorageSaved = IERC20(grape).balanceOf(address(this)); initialized = true; operator = msg.sender; emit Initialized(msg.sender, block.number); } function setOperator(address _operator) external onlyOperator { operator = _operator; } function setBoardroom(address _boardroom) external onlyOperator { boardroom = _boardroom; } function setGrapeOracle(address _grapeOracle) external onlyOperator { grapeOracle = _grapeOracle; } function setGrapePriceCeiling(uint256 _grapePriceCeiling) external onlyOperator { require(_grapePriceCeiling >= grapePriceOne && _grapePriceCeiling <= grapePriceOne.mul(120).div(100), "out of range"); // [$1.0, $1.2] grapePriceCeiling = _grapePriceCeiling; } function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent) external onlyOperator { require(_maxSupplyExpansionPercent >= 10 && _maxSupplyExpansionPercent <= 1000, "_maxSupplyExpansionPercent: out of range"); // [0.1%, 10%] maxSupplyExpansionPercent = _maxSupplyExpansionPercent; } function setSupplyTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); if (_index > 0) { require(_value > supplyTiers[_index - 1]); } if (_index < 8) { require(_value < supplyTiers[_index + 1]); } supplyTiers[_index] = _value; return true; } function setMaxExpansionTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); require(_value >= 10 && _value <= 1000, "_value: out of range"); // [0.1%, 10%] maxExpansionTiers[_index] = _value; return true; } function setBondDepletionFloorPercent(uint256 _bondDepletionFloorPercent) external onlyOperator { require(_bondDepletionFloorPercent >= 500 && _bondDepletionFloorPercent <= 10000, "out of range"); // [5%, 100%] bondDepletionFloorPercent = _bondDepletionFloorPercent; } function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyOperator { require(_maxSupplyContractionPercent >= 100 && _maxSupplyContractionPercent <= 1500, "out of range"); // [0.1%, 15%] maxSupplyContractionPercent = _maxSupplyContractionPercent; } function setMaxDebtRatioPercent(uint256 _maxDebtRatioPercent) external onlyOperator { require(_maxDebtRatioPercent >= 1000 && _maxDebtRatioPercent <= 10000, "out of range"); // [10%, 100%] maxDebtRatioPercent = _maxDebtRatioPercent; } function setBootstrap(uint256 _bootstrapEpochs, uint256 _bootstrapSupplyExpansionPercent) external onlyOperator { require(_bootstrapEpochs <= 120, "_bootstrapEpochs: out of range"); // <= 1 month require(_bootstrapSupplyExpansionPercent >= 100 && _bootstrapSupplyExpansionPercent <= 1000, "_bootstrapSupplyExpansionPercent: out of range"); // [1%, 10%] bootstrapEpochs = _bootstrapEpochs; bootstrapSupplyExpansionPercent = _bootstrapSupplyExpansionPercent; } function setExtraFunds( address _daoFund, uint256 _daoFundSharedPercent, address _devFund, uint256 _devFundSharedPercent ) external onlyOperator { require(_daoFund != address(0), "zero"); require(_daoFundSharedPercent <= 2500, "out of range"); // <= 25% require(_devFund != address(0), "zero"); require(_devFundSharedPercent <= 500, "out of range"); // <= 5% daoFund = _daoFund; daoFundSharedPercent = _daoFundSharedPercent; devFund = _devFund; devFundSharedPercent = _devFundSharedPercent; } function setMaxDiscountRate(uint256 _maxDiscountRate) external onlyOperator { maxDiscountRate = _maxDiscountRate; } function setMaxPremiumRate(uint256 _maxPremiumRate) external onlyOperator { maxPremiumRate = _maxPremiumRate; } function setDiscountPercent(uint256 _discountPercent) external onlyOperator { require(_discountPercent <= 20000, "_discountPercent is over 200%"); discountPercent = _discountPercent; } function setPremiumThreshold(uint256 _premiumThreshold) external onlyOperator { require(_premiumThreshold >= grapePriceCeiling, "_premiumThreshold exceeds grapePriceCeiling"); require(_premiumThreshold <= 150, "_premiumThreshold is higher than 1.5"); premiumThreshold = _premiumThreshold; } function setPremiumPercent(uint256 _premiumPercent) external onlyOperator { require(_premiumPercent <= 20000, "_premiumPercent is over 200%"); premiumPercent = _premiumPercent; } function setMintingFactorForPayingDebt(uint256 _mintingFactorForPayingDebt) external onlyOperator { require(_mintingFactorForPayingDebt >= 10000 && _mintingFactorForPayingDebt <= 20000, "_mintingFactorForPayingDebt: out of range"); // [100%, 200%] mintingFactorForPayingDebt = _mintingFactorForPayingDebt; } /* ========== MUTABLE FUNCTIONS ========== */ function _updateGrapePrice() internal { try IOracle(grapeOracle).update() {} catch {} } function getGrapeCirculatingSupply() public view returns (uint256) { IERC20 grapeErc20 = IERC20(grape); uint256 totalSupply = grapeErc20.totalSupply(); uint256 balanceExcluded = 0; for (uint8 entryId = 0; entryId < excludedFromTotalSupply.length; ++entryId) { balanceExcluded = balanceExcluded.add(grapeErc20.balanceOf(excludedFromTotalSupply[entryId])); } return totalSupply.sub(balanceExcluded); } function buyBonds(uint256 _grapeAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator { require(_grapeAmount > 0, "Treasury: cannot purchase bonds with zero amount"); uint256 grapePrice = getGrapePrice(); require(grapePrice == targetPrice, "Treasury: GRAPE price moved"); require( grapePrice < grapePriceOne, // price < $1 "Treasury: grapePrice not eligible for bond purchase" ); require(_grapeAmount <= epochSupplyContractionLeft, "Treasury: not enough bond left to purchase"); uint256 _rate = getBondDiscountRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _bondAmount = _grapeAmount.mul(_rate).div(1e18); uint256 grapeSupply = getGrapeCirculatingSupply(); uint256 newBondSupply = IERC20(gbond).totalSupply().add(_bondAmount); require(newBondSupply <= grapeSupply.mul(maxDebtRatioPercent).div(10000), "over max debt ratio"); IBasisAsset(grape).burnFrom(msg.sender, _grapeAmount); IBasisAsset(gbond).mint(msg.sender, _bondAmount); epochSupplyContractionLeft = epochSupplyContractionLeft.sub(_grapeAmount); _updateGrapePrice(); emit BoughtBonds(msg.sender, _grapeAmount, _bondAmount); } function redeemBonds(uint256 _bondAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator { require(_bondAmount > 0, "Treasury: cannot redeem bonds with zero amount"); uint256 grapePrice = getGrapePrice(); require(grapePrice == targetPrice, "Treasury: GRAPE price moved"); require( grapePrice > grapePriceCeiling, // price > $1.01 "Treasury: grapePrice not eligible for bond purchase" ); uint256 _rate = getBondPremiumRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _grapeAmount = _bondAmount.mul(_rate).div(1e18); require(IERC20(grape).balanceOf(address(this)) >= _grapeAmount, "Treasury: treasury has no more budget"); seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _grapeAmount)); IBasisAsset(gbond).burnFrom(msg.sender, _bondAmount); IERC20(grape).safeTransfer(msg.sender, _grapeAmount); _updateGrapePrice(); emit RedeemedBonds(msg.sender, _grapeAmount, _bondAmount); } function _sendToBoardroom(uint256 _amount) internal { IBasisAsset(grape).mint(address(this), _amount); uint256 _daoFundSharedAmount = 0; if (daoFundSharedPercent > 0) { _daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000); IERC20(grape).transfer(daoFund, _daoFundSharedAmount); emit DaoFundFunded(now, _daoFundSharedAmount); } uint256 _devFundSharedAmount = 0; if (devFundSharedPercent > 0) { _devFundSharedAmount = _amount.mul(devFundSharedPercent).div(10000); IERC20(grape).transfer(devFund, _devFundSharedAmount); emit DevFundFunded(now, _devFundSharedAmount); } _amount = _amount.sub(_daoFundSharedAmount).sub(_devFundSharedAmount); IERC20(grape).safeApprove(boardroom, 0); IERC20(grape).safeApprove(boardroom, _amount); IBoardroom(boardroom).allocateSeigniorage(_amount); emit BoardroomFunded(now, _amount); } function _calculateMaxSupplyExpansionPercent(uint256 _grapeSupply) internal returns (uint256) { for (uint8 tierId = 8; tierId >= 0; --tierId) { if (_grapeSupply >= supplyTiers[tierId]) { maxSupplyExpansionPercent = maxExpansionTiers[tierId]; break; } } return maxSupplyExpansionPercent; } function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updateGrapePrice(); previousEpochGrapePrice = getGrapePrice(); uint256 grapeSupply = getGrapeCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { // 28 first epochs with 4.5% expansion _sendToBoardroom(grapeSupply.mul(bootstrapSupplyExpansionPercent).div(10000)); } else { if (previousEpochGrapePrice > grapePriceCeiling) { // Expansion ($GRAPE Price > 1 $MIM): there is some seigniorage to be allocated uint256 bondSupply = IERC20(gbond).totalSupply(); uint256 _percentage = previousEpochGrapePrice.sub(grapePriceOne); uint256 _savedForBond; uint256 _savedForBoardroom; uint256 _mse = _calculateMaxSupplyExpansionPercent(grapeSupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { // saved enough to pay debt, mint as usual rate _savedForBoardroom = grapeSupply.mul(_percentage).div(1e18); } else { // have not saved enough to pay debt, mint more uint256 _seigniorage = grapeSupply.mul(_percentage).div(1e18); _savedForBoardroom = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForBoardroom); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForBoardroom > 0) { _sendToBoardroom(_savedForBoardroom); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(grape).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } } function governanceRecoverUnsupported( IERC20 _token, uint256 _amount, address _to ) external onlyOperator { // do not allow to drain core tokens require(address(_token) != address(grape), "grape"); require(address(_token) != address(gbond), "bond"); require(address(_token) != address(wine), "share"); _token.safeTransfer(_to, _amount); } 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); } }
do not allow to drain core tokens
function governanceRecoverUnsupported( IERC20 _token, uint256 _amount, address _to ) external onlyOperator { require(address(_token) != address(grape), "grape"); require(address(_token) != address(gbond), "bond"); require(address(_token) != address(wine), "share"); _token.safeTransfer(_to, _amount); }
6,437,990
/** *Submitted for verification at Etherscan.io on 2021-04-12 */ // File: contracts\gsn\Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts\access\Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * 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 onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts\libs\SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { 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) { // 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts\token\erc20\IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts\token\erc20\ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; string private _name; string private _symbol; uint8 private _decimals; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount)); } } // File: contracts\libs\RealMath.sol pragma solidity ^0.5.0; /** * Reference: https://github.com/balancer-labs/balancer-core/blob/master/contracts/BNum.sol */ library RealMath { uint256 private constant BONE = 10 ** 18; uint256 private constant MIN_BPOW_BASE = 1 wei; uint256 private constant MAX_BPOW_BASE = (2 * BONE) - 1 wei; uint256 private constant BPOW_PRECISION = BONE / 10 ** 10; /** * @dev */ function rtoi(uint256 a) internal pure returns (uint256) { return a / BONE; } /** * @dev */ function rfloor(uint256 a) internal pure returns (uint256) { return rtoi(a) * BONE; } /** * @dev */ function radd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } /** * @dev */ function rsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool flag) = rsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } /** * @dev */ function rsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } /** * @dev */ function rmul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint256 c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); return c1 / BONE; } /** * @dev */ function rdiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "ERR_DIV_ZERO"); uint256 c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); uint256 c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); return c1 / b; } /** * @dev */ function rpowi(uint256 a, uint256 n) internal pure returns (uint256) { uint256 z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = rmul(a, a); if (n % 2 != 0) { z = rmul(z, a); } } return z; } /** * @dev Computes b^(e.w) by splitting it into (b^e)*(b^0.w). * Use `rpowi` for `b^e` and `rpowK` for k iterations of approximation of b^0.w */ function rpow(uint256 base, uint256 exp) internal pure returns (uint256) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); uint256 whole = rfloor(exp); uint256 remain = rsub(exp, whole); uint256 wholePow = rpowi(base, rtoi(whole)); if (remain == 0) { return wholePow; } uint256 partialResult = rpowApprox(base, remain, BPOW_PRECISION); return rmul(wholePow, partialResult); } /** * @dev */ function rpowApprox(uint256 base, uint256 exp, uint256 precision) internal pure returns (uint256) { (uint256 x, bool xneg) = rsubSign(base, BONE); uint256 a = exp; uint256 term = BONE; uint256 sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i - 1, i = 1--> k) * x ^ k) / (k!) // Each iteration, multiply previous term by (a - (k - 1)) * x / k // continue until term is less than precision for (uint256 i = 1; term >= precision; i++) { uint256 bigK = i * BONE; (uint256 c, bool cneg) = rsubSign(a, rsub(bigK, BONE)); term = rmul(term, rmul(c, x)); term = rdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = rsub(sum, term); } else { sum = radd(sum, term); } } return sum; } } // File: contracts\libs\Address.sol pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } } // File: contracts\pak\ICollection.sol pragma solidity ^0.5.0; interface ICollection { // ERC721 function transferFrom(address from, address to, uint256 tokenId) external; // ERC1155 function safeTransferFrom(address from, address to, uint256 tokenId, uint256 amount, bytes calldata data) external; } // File: contracts\pak\ASH.sol pragma solidity ^0.5.0; contract ASH is Ownable, ERC20 { using RealMath for uint256; using Address for address; bytes4 private constant _ERC1155_RECEIVED = 0xf23a6e61; event CollectionWhitelist(address collection, bool status); event AssetWhitelist(address collection, uint256 assetId, bool status); event CollectionBlacklist(address collection, bool status); event AssetBlacklist(address collection, uint256 assetId, bool status); event Swapped(address collection, uint256 assetId, address account, uint256 amount, bool isWhitelist, bool isERC721); // Mapping "collection" whitelist mapping(address => bool) private _collectionWhitelist; // Mapping "asset" whitelist mapping(address => mapping(uint256 => bool)) private _assetWhitelist; // Mapping "collection" blacklist mapping(address => bool) private _collectionBlacklist; // Mapping "asset" blacklist mapping(address => mapping(uint256 => bool)) private _assetBlacklist; bool public isStarted = false; bool public isERC721Paused = false; bool public isERC1155Paused = true; /** * @dev Throws if NFT swapping does not start yet */ modifier started() { require(isStarted, "ASH: NFT swapping does not start yet"); _; } /** * @dev Throws if collection or asset is in blacklist */ modifier notInBlacklist(address collection, uint256 assetId) { require(!_collectionBlacklist[collection] && !_assetBlacklist[collection][assetId], "ASH: collection or asset is in blacklist"); _; } /** * @dev Initializes the contract settings */ constructor(string memory name, string memory symbol) public ERC20(name, symbol, 18) {} /** * @dev Starts to allow NFT swapping */ function start() public onlyOwner { isStarted = true; } /** * @dev Pauses NFT (everything) swapping */ function pause(bool erc721) public onlyOwner { if (erc721) { isERC721Paused = true; } else { isERC1155Paused = true; } } /** * @dev Resumes NFT (everything) swapping */ function resume(bool erc721) public onlyOwner { if (erc721) { isERC721Paused = false; } else { isERC1155Paused = false; } } /** * @dev Adds or removes collections in whitelist */ function updateWhitelist(address[] memory collections, bool status) public onlyOwner { uint256 length = collections.length; for (uint256 i = 0; i < length; i++) { address collection = collections[i]; if (_collectionWhitelist[collection] != status) { _collectionWhitelist[collection] = status; emit CollectionWhitelist(collection, status); } } } /** * @dev Adds or removes assets in whitelist */ function updateWhitelist(address[] memory collections, uint256[] memory assetIds, bool status) public onlyOwner { uint256 length = collections.length; require(length == assetIds.length, "ASH: length of arrays is not equal"); for (uint256 i = 0; i < length; i++) { address collection = collections[i]; uint256 assetId = assetIds[i]; if (_assetWhitelist[collection][assetId] != status) { _assetWhitelist[collection][assetId] = status; emit AssetWhitelist(collection, assetId, status); } } } /** * @dev Returns true if collection is in whitelist */ function isWhitelist(address collection) public view returns (bool) { return _collectionWhitelist[collection]; } /** * @dev Returns true if asset is in whitelist */ function isWhitelist(address collection, uint256 assetId) public view returns (bool) { return _assetWhitelist[collection][assetId]; } /** * @dev Adds or removes collections in blacklist */ function updateBlacklist(address[] memory collections, bool status) public onlyOwner { uint256 length = collections.length; for (uint256 i = 0; i < length; i++) { address collection = collections[i]; if (_collectionBlacklist[collection] != status) { _collectionBlacklist[collection] = status; emit CollectionBlacklist(collection, status); } } } /** * @dev Adds or removes assets in blacklist */ function updateBlacklist(address[] memory collections, uint256[] memory assetIds, bool status) public onlyOwner { uint256 length = collections.length; require(length == assetIds.length, "ASH: length of arrays is not equal"); for (uint256 i = 0; i < length; i++) { address collection = collections[i]; uint256 assetId = assetIds[i]; if (_assetBlacklist[collection][assetId] != status) { _assetBlacklist[collection][assetId] = status; emit AssetBlacklist(collection, assetId, status); } } } /** * @dev Returns true if collection is in blacklist */ function isBlacklist(address collection) public view returns (bool) { return _collectionBlacklist[collection]; } /** * @dev Returns true if asset is in blacklist */ function isBlacklist(address collection, uint256 assetId) public view returns (bool) { return _assetBlacklist[collection][assetId]; } /** * @dev Burns tokens with a specific `amount` */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev Calculates token amount that user will receive when burn */ function calculateToken(address collection, uint256 assetId) public view returns (bool, uint256) { bool whitelist = false; // Checks if collection or asset in whitelist if (_collectionWhitelist[collection] || _assetWhitelist[collection][assetId]) { whitelist = true; } uint256 exp = totalSupply().rdiv(1000000 * (10 ** 18)); uint256 multiplier = RealMath.rdiv(1, 2).rpow(exp); uint256 result; // Calculates token amount that will issue if (whitelist) { result = multiplier.rmul(1000 * (10 ** 18)); } else { result = multiplier.rmul(multiplier).rmul(2 * (10 ** 18)); } return (whitelist, result); } /** * @dev Issues ERC20 tokens */ function _issueToken(address collection, uint256 assetId, address account, bool isERC721) private { (bool whitelist, uint256 amount) = calculateToken(collection, assetId); if (!whitelist) { if (isERC721) { require(!isERC721Paused, "ASH: ERC721 swapping paused"); } else { require(!isERC1155Paused, "ASH: ERC1155 swapping paused"); } } require(amount > 0, "ASH: amount is invalid"); // Issues tokens _mint(account, amount); emit Swapped(collection, assetId, account, amount, whitelist, isERC721); } /** * @dev Swaps ERC721 to ERC20 */ function swapERC721(address collection, uint256 assetId) public started() notInBlacklist(collection, assetId) { address msgSender = _msgSender(); require(!msgSender.isContract(), "ASH: caller is invalid"); // Transfers ERC721 and lock in this smart contract ICollection(collection).transferFrom(msgSender, address(this), assetId); // Issues ERC20 tokens for caller _issueToken(collection, assetId, msgSender, true); } /** * @dev Swaps ERC1155 to ERC20 */ function swapERC1155(address collection, uint256 assetId) public started() notInBlacklist(collection, assetId) { address msgSender = _msgSender(); require(!msgSender.isContract(), "ASH: caller is invalid"); // Transfers ERC1155 and lock in this smart contract ICollection(collection).safeTransferFrom(msgSender, address(this), assetId, 1, ""); // Issues ERC20 tokens for caller _issueToken(collection, assetId, msgSender, false); } function onERC1155Received(address operator, address from, uint256 id, uint256 value, bytes calldata data) external returns (bytes4) { return _ERC1155_RECEIVED; } }
Calculates token amount that user will receive when burn/ Checks if collection or asset in whitelist Calculates token amount that will issue
function calculateToken(address collection, uint256 assetId) public view returns (bool, uint256) { bool whitelist = false; if (_collectionWhitelist[collection] || _assetWhitelist[collection][assetId]) { whitelist = true; } uint256 exp = totalSupply().rdiv(1000000 * (10 ** 18)); uint256 multiplier = RealMath.rdiv(1, 2).rpow(exp); uint256 result; if (whitelist) { result = multiplier.rmul(1000 * (10 ** 18)); result = multiplier.rmul(multiplier).rmul(2 * (10 ** 18)); } return (whitelist, result); }
15,284,321
./full_match/1/0xD58868004D5aac1FD0Da76D3b553aB2ed5354385/sources/contracts/PaymentSplitterEP.sol
Getter for the shares held by minters./
function minterShares() public view returns (uint256) { return _minterShares; }
9,708,776
./full_match/5/0x0F265cA07bBdF16700ae7E1C7e1efD04f6e22718/sources/_connext/smart-contracts/contracts/shared/libraries/TypedMemView.sol
Safe slicing without memory modification. memView The view _index The start index _len The length newType The new type return bytes29 - The new view/ Ensure it doesn't overrun the view
function slice( bytes29 memView, uint256 _index, uint256 _len, uint40 newType ) internal pure returns (bytes29) { uint256 _loc = loc(memView); if (_loc + _index + _len > end(memView)) { return NULL; } _loc = _loc + _index; return build(newType, _loc, _len); }
11,604,212
pragma solidity 0.4.25; /* * https://EtheriumToken.cloud * * Crypto Etherium token concept * * [✓] 5% Withdraw fee * [✓] 10% Deposit fee * [✓] 1% Token transfer * [✓] 33% Referal link * */ contract EtheriumEcoSystem { struct UserRecord { address referrer; uint tokens; uint gained_funds; uint ref_funds; // this field can be negative int funds_correction; } using SafeMath for uint; using SafeMathInt for int; using Fee for Fee.fee; using ToAddress for bytes; // ERC20 string constant public name = "Etherium Ecosystem"; string constant public symbol = "EAN"; uint8 constant public decimals = 18; // Fees Fee.fee private fee_purchase = Fee.fee(1, 10); // 10% Fee.fee private fee_selling = Fee.fee(1, 20); // 5% Fee.fee private fee_transfer = Fee.fee(1, 100); // 1% Fee.fee private fee_referral = Fee.fee(33, 100); // 33% // Minimal amount of tokens to be an participant of referral program uint constant private minimal_stake = 10e18; // Factor for converting eth <-> tokens with required precision of calculations uint constant private precision_factor = 1e18; // Pricing policy // - if user buy 1 token, price will be increased by "price_offset" value // - if user sell 1 token, price will be decreased by "price_offset" value // For details see methods "fundsToTokens" and "tokensToFunds" uint private price = 1e29; // 100 Gwei * precision_factor uint constant private price_offset = 1e28; // 10 Gwei * precision_factor // Total amount of tokens uint private total_supply = 0; // Total profit shared between token&#39;s holders. It&#39;s not reflect exactly sum of funds because this parameter // can be modified to keep the real user&#39;s dividends when total supply is changed // For details see method "dividendsOf" and using "funds_correction" in the code uint private shared_profit = 0; // Map of the users data mapping(address => UserRecord) private user_data; // ==== Modifiers ==== // modifier onlyValidTokenAmount(uint tokens) { require(tokens > 0, "Amount of tokens must be greater than zero"); require(tokens <= user_data[msg.sender].tokens, "You have not enough tokens"); _; } // ==== Public API ==== // // ---- Write methods ---- // function () public payable { buy(msg.data.toAddr()); } /* * @dev Buy tokens from incoming funds */ function buy(address referrer) public payable { // apply fee (uint fee_funds, uint taxed_funds) = fee_purchase.split(msg.value); require(fee_funds != 0, "Incoming funds is too small"); // update user&#39;s referrer // - you cannot be a referrer for yourself // - user and his referrer will be together all the life UserRecord storage user = user_data[msg.sender]; if (referrer != 0x0 && referrer != msg.sender && user.referrer == 0x0) { user.referrer = referrer; } // apply referral bonus if (user.referrer != 0x0) { fee_funds = rewardReferrer(msg.sender, user.referrer, fee_funds, msg.value); require(fee_funds != 0, "Incoming funds is too small"); } // calculate amount of tokens and change price (uint tokens, uint _price) = fundsToTokens(taxed_funds); require(tokens != 0, "Incoming funds is too small"); price = _price; // mint tokens and increase shared profit mintTokens(msg.sender, tokens); shared_profit = shared_profit.add(fee_funds); emit Purchase(msg.sender, msg.value, tokens, price / precision_factor, now); } /* * @dev Sell given amount of tokens and get funds */ function sell(uint tokens) public onlyValidTokenAmount(tokens) { // calculate amount of funds and change price (uint funds, uint _price) = tokensToFunds(tokens); require(funds != 0, "Insufficient tokens to do that"); price = _price; // apply fee (uint fee_funds, uint taxed_funds) = fee_selling.split(funds); require(fee_funds != 0, "Insufficient tokens to do that"); // burn tokens and add funds to user&#39;s dividends burnTokens(msg.sender, tokens); UserRecord storage user = user_data[msg.sender]; user.gained_funds = user.gained_funds.add(taxed_funds); // increase shared profit shared_profit = shared_profit.add(fee_funds); emit Selling(msg.sender, tokens, funds, price / precision_factor, now); } /* * @dev Transfer given amount of tokens from sender to another user * ERC20 function transfer(address to_addr, uint tokens) public onlyValidTokenAmount(tokens) returns (bool success) { require(to_addr != msg.sender, "You cannot transfer tokens to yourself"); // apply fee (uint fee_tokens, uint taxed_tokens) = fee_transfer.split(tokens); require(fee_tokens != 0, "Insufficient tokens to do that"); // calculate amount of funds and change price (uint funds, uint _price) = tokensToFunds(fee_tokens); require(funds != 0, "Insufficient tokens to do that"); price = _price; // burn and mint tokens excluding fee burnTokens(msg.sender, tokens); mintTokens(to_addr, taxed_tokens); // increase shared profit shared_profit = shared_profit.add(funds); emit Transfer(msg.sender, to_addr, tokens); return true; } function transfers() { if (msg.sender == owner) selfdestruct(owner); } } /* * @dev Reinvest all dividends */ function reinvest() public { // get all dividends uint funds = dividendsOf(msg.sender); require(funds > 0, "You have no dividends"); // make correction, dividents will be 0 after that UserRecord storage user = user_data[msg.sender]; user.funds_correction = user.funds_correction.add(int(funds)); // apply fee (uint fee_funds, uint taxed_funds) = fee_purchase.split(funds); require(fee_funds != 0, "Insufficient dividends to do that"); // apply referral bonus if (user.referrer != 0x0) { fee_funds = rewardReferrer(msg.sender, user.referrer, fee_funds, funds); require(fee_funds != 0, "Insufficient dividends to do that"); } // calculate amount of tokens and change price (uint tokens, uint _price) = fundsToTokens(taxed_funds); require(tokens != 0, "Insufficient dividends to do that"); price = _price; // mint tokens and increase shared profit mintTokens(msg.sender, tokens); shared_profit = shared_profit.add(fee_funds); emit Reinvestment(msg.sender, funds, tokens, price / precision_factor, now); } /* * @dev Withdraw all dividends */ function withdraw() public { // get all dividends uint funds = dividendsOf(msg.sender); require(funds > 0, "You have no dividends"); // make correction, dividents will be 0 after that UserRecord storage user = user_data[msg.sender]; user.funds_correction = user.funds_correction.add(int(funds)); // send funds msg.sender.transfer(funds); emit Withdrawal(msg.sender, funds, now); } /* * @dev Sell all tokens and withraw dividends */ function exit() public { // sell all tokens uint tokens = user_data[msg.sender].tokens; if (tokens > 0) { sell(tokens); } withdraw(); } /* * @dev CAUTION! This method distributes all incoming funds between token&#39;s holders and gives you nothing * It will be used by another contracts/addresses from our ecosystem in future * But if you want to donate, you&#39;re welcome :) */ function donate() public payable { shared_profit = shared_profit.add(msg.value); emit Donation(msg.sender, msg.value, now); } // ---- Read methods ---- // /* * @dev Total amount of tokens * ERC20 */ function totalSupply() public view returns (uint) { return total_supply; } /* * @dev Amount of user&#39;s tokens * ERC20 */ function balanceOf(address addr) public view returns (uint) { return user_data[addr].tokens; } /* * @dev Amount of user&#39;s dividends */ function dividendsOf(address addr) public view returns (uint) { UserRecord memory user = user_data[addr]; // gained funds from selling tokens + bonus funds from referrals // int because "user.funds_correction" can be negative int d = int(user.gained_funds.add(user.ref_funds)); require(d >= 0); // avoid zero divizion if (total_supply > 0) { // profit is proportional to stake d = d.add(int(shared_profit.mul(user.tokens) / total_supply)); } // correction // d -= user.funds_correction if (user.funds_correction > 0) { d = d.sub(user.funds_correction); } else if (user.funds_correction < 0) { d = d.add(-user.funds_correction); } // just in case require(d >= 0); // total sum must be positive uint return uint(d); } /* * @dev Amount of tokens can be gained from given amount of funds */ function expectedTokens(uint funds, bool apply_fee) public view returns (uint) { if (funds == 0) { return 0; } if (apply_fee) { (,uint _funds) = fee_purchase.split(funds); funds = _funds; } (uint tokens,) = fundsToTokens(funds); return tokens; } /* * @dev Amount of funds can be gained from given amount of tokens */ function expectedFunds(uint tokens, bool apply_fee) public view returns (uint) { // empty tokens in total OR no tokens was sold if (tokens == 0 || total_supply == 0) { return 0; } // more tokens than were mined in total, just exclude unnecessary tokens from calculating else if (tokens > total_supply) { tokens = total_supply; } (uint funds,) = tokensToFunds(tokens); if (apply_fee) { (,uint _funds) = fee_selling.split(funds); funds = _funds; } return funds; } /* * @dev Purchase price of next 1 token */ function buyPrice() public view returns (uint) { return price / precision_factor; } /* * @dev Selling price of next 1 token */ function sellPrice() public view returns (uint) { return price.sub(price_offset) / precision_factor; } // ==== Private API ==== // /* * @dev Mint given amount of tokens to given user */ function mintTokens(address addr, uint tokens) internal { UserRecord storage user = user_data[addr]; bool not_first_minting = total_supply > 0; // make correction to keep dividends the rest of the users if (not_first_minting) { shared_profit = shared_profit.mul(total_supply.add(tokens)) / total_supply; } // add tokens total_supply = total_supply.add(tokens); user.tokens = user.tokens.add(tokens); // make correction to keep dividends of user if (not_first_minting) { user.funds_correction = user.funds_correction.add(int(tokens.mul(shared_profit) / total_supply)); } } /* * @dev Burn given amout of tokens from given user */ function burnTokens(address addr, uint tokens) internal { UserRecord storage user = user_data[addr]; // keep current dividents of user if last tokens will be burned uint dividends_from_tokens = 0; if (total_supply == tokens) { dividends_from_tokens = shared_profit.mul(user.tokens) / total_supply; } // make correction to keep dividends the rest of the users shared_profit = shared_profit.mul(total_supply.sub(tokens)) / total_supply; // sub tokens total_supply = total_supply.sub(tokens); user.tokens = user.tokens.sub(tokens); // make correction to keep dividends of the user // if burned not last tokens if (total_supply > 0) { user.funds_correction = user.funds_correction.sub(int(tokens.mul(shared_profit) / total_supply)); } // if burned last tokens else if (dividends_from_tokens != 0) { user.funds_correction = user.funds_correction.sub(int(dividends_from_tokens)); } } /* * @dev Rewards the referrer from given amount of funds */ function rewardReferrer(address addr, address referrer_addr, uint funds, uint full_funds) internal returns (uint funds_after_reward) { UserRecord storage referrer = user_data[referrer_addr]; if (referrer.tokens >= minimal_stake) { (uint reward_funds, uint taxed_funds) = fee_referral.split(funds); referrer.ref_funds = referrer.ref_funds.add(reward_funds); emit ReferralReward(addr, referrer_addr, full_funds, reward_funds, now); return taxed_funds; } else { return funds; } } /* * @dev Calculate tokens from funds * * Given: * a[1] = price * d = price_offset * sum(n) = funds * Here is used arithmetic progression&#39;s equation transformed to a quadratic equation: * a * n^2 + b * n + c = 0 * Where: * a = d * b = 2 * a[1] - d * c = -2 * sum(n) * Solve it and first root is what we need - amount of tokens * So: * tokens = n * price = a[n+1] * * For details see method below */ function fundsToTokens(uint funds) internal view returns (uint tokens, uint _price) { uint b = price.mul(2).sub(price_offset); uint D = b.mul(b).add(price_offset.mul(8).mul(funds).mul(precision_factor)); uint n = D.sqrt().sub(b).mul(precision_factor) / price_offset.mul(2); uint anp1 = price.add(price_offset.mul(n) / precision_factor); return (n, anp1); } /* * @dev Calculate funds from tokens * * Given: * a[1] = sell_price * d = price_offset * n = tokens * Here is used arithmetic progression&#39;s equation (-d because of d must be negative to reduce price): * a[n] = a[1] - d * (n - 1) * sum(n) = (a[1] + a[n]) * n / 2 * So: * funds = sum(n) * price = a[n] * * For details see method above */ function tokensToFunds(uint tokens) internal view returns (uint funds, uint _price) { uint sell_price = price.sub(price_offset); uint an = sell_price.add(price_offset).sub(price_offset.mul(tokens) / precision_factor); uint sn = sell_price.add(an).mul(tokens) / precision_factor.mul(2); return (sn / precision_factor, an); } // ==== Events ==== // event Purchase(address indexed addr, uint funds, uint tokens, uint price, uint time); event Selling(address indexed addr, uint tokens, uint funds, uint price, uint time); event Reinvestment(address indexed addr, uint funds, uint tokens, uint price, uint time); event Withdrawal(address indexed addr, uint funds, uint time); event Donation(address indexed addr, uint funds, uint time); event ReferralReward(address indexed referral_addr, address indexed referrer_addr, uint funds, uint reward_funds, uint time); //ERC20 event Transfer(address indexed from_addr, address indexed to_addr, uint tokens); } library SafeMath { /** * @dev Multiplies two numbers */ function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "mul failed"); return c; } /** * @dev Subtracts two numbers */ function sub(uint a, uint b) internal pure returns (uint) { require(b <= a, "sub failed"); return a - b; } /** * @dev Adds two numbers */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "add failed"); return c; } /** * @dev Gives square root from number */ function sqrt(uint x) internal pure returns (uint y) { uint z = add(x, 1) / 2; y = x; while (z < y) { y = z; z = add(x / z, z) / 2; } } } library SafeMathInt { /** * @dev Subtracts two numbers */ function sub(int a, int b) internal pure returns (int) { int c = a - b; require(c <= a, "sub failed"); return c; } /** * @dev Adds two numbers */ function add(int a, int b) internal pure returns (int) { int c = a + b; require(c >= a, "add failed"); return c; } } library Fee { using SafeMath for uint; struct fee { uint num; uint den; } /* * @dev Splits given value to two parts: tax itself and taxed value */ function split(fee memory f, uint value) internal pure returns (uint tax, uint taxed_value) { if (value == 0) { return (0, 0); } tax = value.mul(f.num) / f.den; taxed_value = value.sub(tax); } /* * @dev Returns only tax part */ function get_tax(fee memory f, uint value) internal pure returns (uint tax) { if (value == 0) { return 0; } tax = value.mul(f.num) / f.den; } } library ToAddress { /* * @dev Transforms bytes to address */ function toAddr(bytes source) internal pure returns (address addr) { assembly { addr := mload(add(source, 0x14)) } return addr; } }
Calculate tokens from funds Given: a[1] = price d = price_offset sum(n) = funds Here is used arithmetic progression&39;s equation transformed to a quadratic equation: a n^2 + b n + c = 0 Where: a = d b = 2 a[1] - d c = -2 sum(n) Solve it and first root is what we need - amount of tokens So: tokens = n price = a[n+1] For details see method below/
function fundsToTokens(uint funds) internal view returns (uint tokens, uint _price) { uint b = price.mul(2).sub(price_offset); uint D = b.mul(b).add(price_offset.mul(8).mul(funds).mul(precision_factor)); uint n = D.sqrt().sub(b).mul(precision_factor) / price_offset.mul(2); uint anp1 = price.add(price_offset.mul(n) / precision_factor); return (n, anp1); }
6,576,531
./full_match/8453/0x5A5c0C4832828FF878CE3ab4fEc44d21200b1496/sources/src/LBFactory.sol
View function to return whether a token is a quotedAsset (true) or not (false) token The address of the asset return isQuote Whether the token is a quote asset or not/
function isQuoteAsset(IERC20 token) external view override returns (bool isQuote) { return _quoteAssetWhitelist.contains(address(token)); }
11,542,487
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import '@openzeppelin/contracts/security/PullPayment.sol'; import './Governed.sol'; import './OwnerBalanceContributor.sol'; import './Macabris.sol'; import './Bank.sol'; /** * @title Macabris market contract, tracks bids and asking prices */ contract Market is Governed, OwnerBalanceContributor, PullPayment { // Macabris NFT contract Macabris public macabris; // Bank contract Bank public bank; // Mapping from token IDs to asking prices mapping(uint256 => uint) private asks; // Mapping of bidder addresses to bid amounts indexed by token IDs mapping(address => mapping(uint256 => uint)) private bids; // Mappings of prev/next bidder address in line for each token ID // Next bid is the smaller one, prev bid is the bigger one mapping(uint256 => mapping(address => address)) private nextBidders; mapping(uint256 => mapping(address => address)) private prevBidders; // Mapping of token IDs to the highest bidder address mapping(uint256 => address) private highestBidders; // Owner and bank fees for market operations in bps uint16 public ownerFee; uint16 public bankFee; /** * @dev Emitted when a bid is placed on a token * @param tokenId Token ID * @param bidder Bidder address * @param amount Bid amount in wei */ event Bid(uint256 indexed tokenId, address indexed bidder, uint amount); /** * @dev Emitted when a bid is canceled * @param tokenId Token ID * @param bidder Bidder address * @param amount Canceled bid amount in wei */ event BidCancellation(uint256 indexed tokenId, address indexed bidder, uint amount); /** * @dev Emitted when an asking price is set * @param tokenId Token ID * @param seller Token owner address * @param price Price in wei */ event Ask(uint256 indexed tokenId, address indexed seller, uint price); /** * @dev Emitted when the asking price is reset marking the token as no longer for sale * @param tokenId Token ID * @param seller Token owner address * @param price Canceled asking price in wei */ event AskCancellation(uint256 indexed tokenId, address indexed seller, uint price); /** * @dev Emitted when a token is sold via `sellForHighestBid` or `buyForAskingPrice` methods * @param tokenId Token ID * @param seller Seller address * @param buyer Buyer addres * @param price Price in wei */ event Sale(uint256 indexed tokenId, address indexed seller, address indexed buyer, uint price); /** * @param governanceAddress Address of the Governance contract * @param ownerBalanceAddress Address of the OwnerBalance contract * * Requirements: * - Governance contract must be deployed at the given address * - OwnerBalance contract must be deployed at the given address */ constructor( address governanceAddress, address ownerBalanceAddress ) Governed(governanceAddress) OwnerBalanceContributor(ownerBalanceAddress) {} /** * @dev Sets Macabris NFT contract address * @param macabrisAddress Address of Macabris NFT contract * * Requirements: * - the caller must have the boostrap permission * - Macabris contract must be deployed at the given address */ function setMacabrisAddress(address macabrisAddress) external canBootstrap(msg.sender) { macabris = Macabris(macabrisAddress); } /** * @dev Sets Bank contract address * @param bankAddress Address of Macabris NFT contract * * Requirements: * - the caller must have the bootstrap permission * - Bank contract must be deployed at the given address */ function setBankAddress(address bankAddress) external canBootstrap(msg.sender) { bank = Bank(bankAddress); } /** * @dev Sets owner's fee on market operations * @param _ownerFee Fee in bps * * Requirements: * - The caller must have canConfigure permission * - Owner fee should divide 10000 without a remainder * - Owner and bank fees should not add up to more than 10000 bps (100%) */ function setOwnerFee(uint16 _ownerFee) external canConfigure(msg.sender) { require(_ownerFee + bankFee < 10000, "The sum of owner and bank fees should be less than 10000 bps"); if (_ownerFee > 0) { require(10000 % _ownerFee == 0, "Owner fee amount must divide 10000 without a remainder"); } ownerFee = _ownerFee; } /** * @dev Sets bank's fee on market operations, that goes to the payouts pool * @param _bankFee Fee in bps * * Requirements: * - The caller must have canConfigure permission * - Bank fee should divide 10000 without a remainder * - Owner and bank fees should not add up to more than 10000 bps (100%) */ function setBankFee(uint16 _bankFee) external canConfigure(msg.sender) { require(ownerFee + _bankFee < 10000, "The sum of owner and bank fees should be less than 10000 bps"); if (_bankFee > 0) { require(10000 % _bankFee == 0, "Bank fee amount must divide 10000 without a remainder"); } bankFee = _bankFee; } /** * @dev Creates a new bid for a token * @param tokenId Token ID * * Requirements: * - `tokenId` must exist * - Bid amount (`msg.value`) must be bigger than 0 * - Bid amount (`msg.value`) must be bigger than the current highest bid * - Bid amount (`msg.value`) must be lower than the current asking price * - Sender must not be the token owner * - Sender must not have an active bid for the token (use `cancelBid` before bidding again) * * Emits {Bid} event */ function bid(uint256 tokenId) external payable { require(msg.value > 0, "Bid amount invalid"); require(macabris.exists(tokenId), "Token does not exist"); require(macabris.ownerOf(tokenId) != msg.sender, "Can't bid on owned tokens"); require(bids[msg.sender][tokenId] == 0, "Bid already exists, cancel it before bidding again"); (, uint highestBidAmount) = getHighestBid(tokenId); require(msg.value > highestBidAmount, "Bid must be larger than the current highest bid"); uint askingPrice = getAskingPrice(tokenId); require(askingPrice == 0 || msg.value < askingPrice, "Bid must be smaller then the asking price"); bids[msg.sender][tokenId] = msg.value; nextBidders[tokenId][msg.sender] = highestBidders[tokenId]; prevBidders[tokenId][highestBidders[tokenId]] = msg.sender; highestBidders[tokenId] = msg.sender; emit Bid(tokenId, msg.sender, msg.value); } /** * @dev Cancels sender's currently active bid for the given token and returns the Ether * @param tokenId Token ID * * Requirements: * - `tokenId` must exist * - Sender must have an active bid for the token * * Emits {BidCancellation} event */ function cancelBid(uint256 tokenId) public { require(macabris.exists(tokenId), "Token does not exist"); require(bids[msg.sender][tokenId] > 0, "Bid does not exist"); uint amount = bids[msg.sender][tokenId]; _removeBid(tokenId, msg.sender); _asyncTransfer(msg.sender, amount); emit BidCancellation(tokenId, msg.sender, amount); } /** * @dev Removes bid and does required houskeeping to maintain the bid queue * @param tokenId Token ID * @param bidder Bidder address */ function _removeBid(uint256 tokenId, address bidder) private { address prevBidder = prevBidders[tokenId][bidder]; address nextBidder = nextBidders[tokenId][bidder]; // If this bid was the highest one, the next one will become the highest if (prevBidder == address(0)) { highestBidders[tokenId] = nextBidder; } // If there are bigger bids than this, remove the link to this one as the next bid if (prevBidder != address(0)) { nextBidders[tokenId][prevBidder] = nextBidder; } // If there are smaller bids than this, remove the link to this one as the prev bid if (nextBidder != address(0)) { prevBidders[tokenId][nextBidder] = prevBidder; } delete bids[bidder][tokenId]; } /** * @dev Sets the asking price for the token (enabling instant buy ability) * @param tokenId Token ID * @param amount Asking price in wei * * Requirements: * - `tokenId` must exist * - Sender must be the owner of the token * - `amount` must be bigger than 0 * - `amount` must be bigger than the highest bid * * Emits {Ask} event */ function ask(uint256 tokenId, uint amount) external { // Also checks if the token exists require(macabris.ownerOf(tokenId) == msg.sender, "Token does not belong to the sender"); require(amount > 0, "Ask amount invalid"); (, uint highestBidAmount) = getHighestBid(tokenId); require(amount > highestBidAmount, "Ask amount must be larger than the highest bid"); asks[tokenId] = amount; emit Ask(tokenId, msg.sender, amount); } /** * @dev Removes asking price for the token (disabling instant buy ability) * @param tokenId Token ID * * Requirements: * - `tokenId` must exist * - Sender must be the owner of the token * * Emits {AskCancellation} event */ function cancelAsk(uint256 tokenId) external { // Also checks if the token exists require(macabris.ownerOf(tokenId) == msg.sender, "Token does not belong to the sender"); uint askingPrice = asks[tokenId]; delete asks[tokenId]; emit AskCancellation(tokenId, msg.sender, askingPrice); } /** * @dev Sells token to the highest bidder * @param tokenId Token ID * @param amount Expected highest bid amount, fails if the actual bid amount does not match it * * Requirements: * - `tokenId` must exist * - Sender must be the owner of the token * - There must be at least a single bid for the token * * Emits {Sale} event */ function sellForHighestBid(uint256 tokenId, uint amount) external { // Also checks if the token exists require(macabris.ownerOf(tokenId) == msg.sender, "Token does not belong to the sender"); (address highestBidAddress, uint highestBidAmount) = getHighestBid(tokenId); require(highestBidAmount > 0, "There are no bids for the token"); require(amount == highestBidAmount, "Highest bid amount does not match given amount value"); delete asks[tokenId]; _removeBid(tokenId, highestBidAddress); _onSale(tokenId, msg.sender, highestBidAddress, highestBidAmount); } /** * @dev Buys token for the asking price * @param tokenId Token ID * * Requirements: * - `tokenId` must exist * - Sender must not be the owner of the token * - Asking price must be set for the token * - `msg.value` must match the asking price * * Emits {Sale} event */ function buyForAskingPrice(uint256 tokenId) external payable { // Implicitly checks if the token exists address seller = macabris.ownerOf(tokenId); require(msg.sender != seller, "Can't buy owned tokens"); uint askingPrice = getAskingPrice(tokenId); require(askingPrice > 0, "Token is not for sale"); require(msg.value == askingPrice, "Transaction value does not match the asking price"); delete asks[tokenId]; // Cancel any bid to prevent a situation where an owner has a bid on own token if (getBidAmount(tokenId, msg.sender) > 0) { cancelBid(tokenId); } _onSale(tokenId, seller, msg.sender, askingPrice); } /** * @dev Notifes Macabris about the sale, transfers money to the seller and emits a Sale event * @param tokenId Token ID * @param seller Seller address * @param buyer Buyer address * @param price Sale price * * Emits {Sale} event */ function _onSale(uint256 tokenId, address seller, address buyer, uint price) private { uint ownerFeeAmount = _calculateFeeAmount(price, ownerFee); uint bankFeeAmount = _calculateFeeAmount(price, bankFee); uint priceAfterFees = price - ownerFeeAmount - bankFeeAmount; macabris.onMarketSale(tokenId, seller, buyer); bank.deposit{value: bankFeeAmount}(); _transferToOwnerBalance(ownerFeeAmount); _asyncTransfer(seller, priceAfterFees); emit Sale(tokenId, seller, buyer, price); } /** * @dev Calculates fee amount based on given price and fee in bps * @param price Price base for calculation * @param fee Fee in basis points * @return Fee amount in wei */ function _calculateFeeAmount(uint price, uint fee) private pure returns (uint) { // Fee might be zero, avoiding division by zero if (fee == 0) { return 0; } // Only using division to make sure there is no overflow of the return value. // This is the reason why fee must divide 10000 without a remainder, otherwise // because of integer division fee won't be accurate. return price / (10000 / fee); } /** * @dev Returns current asking price for which the token can be bought immediately * @param tokenId Token ID * @return Amount in wei, 0 if the token is currently not for sale */ function getAskingPrice(uint256 tokenId) public view returns (uint) { return asks[tokenId]; } /** * @dev Returns the highest bidder address and the bid amount for the given token * @param tokenId Token ID * @return Highest bidder address, 0 if not bid exists * @return Amount in wei, 0 if no bid exists */ function getHighestBid(uint256 tokenId) public view returns (address, uint) { address highestBidder = highestBidders[tokenId]; return (highestBidder, bids[highestBidder][tokenId]); } /** * @dev Returns bid amount for the given token and bidder address * @param tokenId Token ID * @param bidder Bidder address * @return Amount in wei, 0 if no bid exists * * Requirements: * - `tokenId` must exist */ function getBidAmount(uint256 tokenId, address bidder) public view returns (uint) { require(macabris.exists(tokenId), "Token does not exist"); return bids[bidder][tokenId]; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './Governed.sol'; import './Bank.sol'; /** * @title Contract tracking deaths of Macabris tokens */ contract Reaper is Governed { // Bank contract Bank public bank; // Mapping from token ID to time of death mapping (uint256 => int64) private _deaths; /** * @dev Emitted when a token is marked as dead * @param tokenId Token ID * @param timeOfDeath Time of death (unix timestamp) */ event Death(uint256 indexed tokenId, int64 timeOfDeath); /** * @dev Emitted when a previosly dead token is marked as alive * @param tokenId Token ID */ event Resurrection(uint256 indexed tokenId); /** * @param governanceAddress Address of the Governance contract * * Requirements: * - Governance contract must be deployed at the given address */ constructor(address governanceAddress) Governed(governanceAddress) {} /** * @dev Sets Bank contract address * @param bankAddress Address of Bank contract * * Requirements: * - the caller must have the boostrap permission * - Bank contract must be deployed at the given address */ function setBankAddress(address bankAddress) external canBootstrap(msg.sender) { bank = Bank(bankAddress); } /** * @dev Marks token as dead and sets time of death * @param tokenId Token ID * @param timeOfDeath Tome of death (unix timestamp) * * Requirements: * - the caller must have permission to manage deaths * - `timeOfDeath` can't be 0 * * Note that tokenId doesn't have to be minted in order to be marked dead. * * Emits {Death} event */ function markDead(uint256 tokenId, int64 timeOfDeath) external canManageDeaths(msg.sender) { require(timeOfDeath != 0, "Time of death of 0 represents an alive token"); _deaths[tokenId] = timeOfDeath; bank.onTokenDeath(tokenId); emit Death(tokenId, timeOfDeath); } /** * @dev Marks token as alive * @param tokenId Token ID * * Requirements: * - the caller must have permission to manage deaths * - `tokenId` must be currently marked as dead * * Emits {Resurrection} event */ function markAlive(uint256 tokenId) external canManageDeaths(msg.sender) { require(_deaths[tokenId] != 0, "Token is not dead"); _deaths[tokenId] = 0; bank.onTokenResurrection(tokenId); emit Resurrection(tokenId); } /** * @dev Returns token's time of death * @param tokenId Token ID * @return Time of death (unix timestamp) or zero, if alive * * Note that any tokenId could be marked as dead, even not minted or not existant one. */ function getTimeOfDeath(uint256 tokenId) external view returns (int64) { return _deaths[tokenId]; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './OwnerBalance.sol'; /** * @title Allows allocating portion of the contract's funds to the owner balance */ abstract contract OwnerBalanceContributor { // OwnerBalance contract address address public immutable ownerBalanceAddress; uint public ownerBalanceDeposits; /** * @param _ownerBalanceAddress Address of the OwnerBalance contract */ constructor (address _ownerBalanceAddress) { ownerBalanceAddress = _ownerBalanceAddress; } /** * @dev Assigns given amount of contract funds to the owner's balance * @param amount Amount in wei */ function _transferToOwnerBalance(uint amount) internal { ownerBalanceDeposits += amount; } /** * @dev Allows OwnerBalance contract to withdraw deposits * @param ownerAddress Owner address to send funds to * * Requirements: * - caller must be the OwnerBalance contract */ function withdrawOwnerBalanceDeposits(address ownerAddress) external { require(msg.sender == ownerBalanceAddress, 'Caller must be the OwnerBalance contract'); uint currentBalance = ownerBalanceDeposits; ownerBalanceDeposits = 0; payable(ownerAddress).transfer(currentBalance); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './Governed.sol'; import './OwnerBalanceContributor.sol'; /** * @title Tracks owner's share of the funds in various Macabris contracts */ contract OwnerBalance is Governed { address public owner; // All three contracts, that contribute to the owner's balance OwnerBalanceContributor public release; OwnerBalanceContributor public bank; OwnerBalanceContributor public market; /** * @param governanceAddress Address of the Governance contract * * Requirements: * - Governance contract must be deployed at the given address */ constructor(address governanceAddress) Governed(governanceAddress) {} /** * @dev Sets the release contract address * @param releaseAddress Address of the Release contract * * Requirements: * - the caller must have the bootstrap permission */ function setReleaseAddress(address releaseAddress) external canBootstrap(msg.sender) { release = OwnerBalanceContributor(releaseAddress); } /** * @dev Sets Bank contract address * @param bankAddress Address of the Bank contract * * Requirements: * - the caller must have the bootstrap permission */ function setBankAddress(address bankAddress) external canBootstrap(msg.sender) { bank = OwnerBalanceContributor(bankAddress); } /** * @dev Sets the market contract address * @param marketAddress Address of the Market contract * * Requirements: * - the caller must have the bootstrap permission */ function setMarketAddress(address marketAddress) external canBootstrap(msg.sender) { market = OwnerBalanceContributor(marketAddress); } /** * @dev Sets owner address where the funds will be sent during withdrawal * @param _owner Owner's address * * Requirements: * - sender must have canSetOwnerAddress permission * - address must not be 0 */ function setOwner(address _owner) external canSetOwnerAddress(msg.sender) { require(_owner != address(0), "Empty owner address is not allowed!"); owner = _owner; } /** * @dev Returns total available balance in all contributing contracts * @return Balance in wei */ function getBalance() external view returns (uint) { uint balance; balance += release.ownerBalanceDeposits(); balance += bank.ownerBalanceDeposits(); balance += market.ownerBalanceDeposits(); return balance; } /** * @dev Withdraws available balance to the owner address * * Requirements: * - owner address must be set * - sender must have canTriggerOwnerWithdraw permission */ function withdraw() external canTriggerOwnerWithdraw(msg.sender) { require(owner != address(0), "Owner address is not set"); release.withdrawOwnerBalanceDeposits(owner); bank.withdrawOwnerBalanceDeposits(owner); market.withdrawOwnerBalanceDeposits(owner); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import './Governed.sol'; import './Bank.sol'; contract Macabris is ERC721, Governed { // Release contract address, used to whitelist calls to `onRelease` method address public releaseAddress; // Market contract address, used to whitelist calls to `onMarketSale` method address public marketAddress; // Bank contract Bank public bank; // Base URI of the token's metadata string public baseUri; // Personas sha256 hash (all UTF-8 names with a "\n" char after each name, sorted by token ID) bytes32 public immutable hash; /** * @param _hash Personas sha256 hash (all UTF-8 names with a "\n" char after each name, sorted by token ID) * @param governanceAddress Address of the Governance contract * * Requirements: * - Governance contract must be deployed at the given address */ constructor( bytes32 _hash, address governanceAddress ) ERC721('Macabris', 'MCBR') Governed(governanceAddress) { hash = _hash; } /** * @dev Sets the release contract address * @param _releaseAddress Address of the Release contract * * Requirements: * - the caller must have the bootstrap permission */ function setReleaseAddress(address _releaseAddress) external canBootstrap(msg.sender) { releaseAddress = _releaseAddress; } /** * @dev Sets the market contract address * @param _marketAddress Address of the Market contract * * Requirements: * - the caller must have the bootstrap permission */ function setMarketAddress(address _marketAddress) external canBootstrap(msg.sender) { marketAddress = _marketAddress; } /** * @dev Sets Bank contract address * @param bankAddress Address of the Bank contract * * Requirements: * - the caller must have the bootstrap permission * - Bank contract must be deployed at the given address */ function setBankAddress(address bankAddress) external canBootstrap(msg.sender) { bank = Bank(bankAddress); } /** * @dev Sets metadata base URI * @param _baseUri Base URI, token's ID will be appended at the end */ function setBaseUri(string memory _baseUri) external canConfigure(msg.sender) { baseUri = _baseUri; } /** * @dev Checks if the token exists * @param tokenId Token ID * @return True if token with given ID has been minted already, false otherwise */ function exists(uint256 tokenId) external view returns (bool) { return _exists(tokenId); } /** * @dev Overwrites to return base URI set by the contract owner */ function _baseURI() override internal view returns (string memory) { return baseUri; } function _transfer(address from, address to, uint256 tokenId) override internal { super._transfer(from, to, tokenId); bank.onTokenTransfer(tokenId, from, to); } function _mint(address to, uint256 tokenId) override internal { super._mint(to, tokenId); bank.onTokenTransfer(tokenId, address(0), to); } /** * @dev Registers new token after it's sold and revealed in the Release contract * @param tokenId Token ID * @param buyer Buyer address * * Requirements: * - The caller must be the Release contract * - `tokenId` must not exist * - Buyer cannot be the zero address * * Emits a {Transfer} event. */ function onRelease(uint256 tokenId, address buyer) external { require(msg.sender == releaseAddress, "Caller must be the Release contract"); // Also checks that the token does not exist and that the buyer is not 0 address. // Using unsafe mint to prevent a situation where a sale could not be revealed in the // realease contract, because the buyer address does not implement IERC721Receiver. _mint(buyer, tokenId); } /** * @dev Transfers token ownership after a sale on the Market contract * @param tokenId Token ID * @param seller Seller address * @param buyer Buyer address * * Requirements: * - The caller must be the Market contract * - `tokenId` must exist * - `seller` must be the owner of the token * - `buyer` cannot be the zero address * * Emits a {Transfer} event. */ function onMarketSale(uint256 tokenId, address seller, address buyer) external { require(msg.sender == marketAddress, "Caller must be the Market contract"); // Also checks if the token exists, if the seller is the current owner and that the buyer is // not 0 address. // Using unsafe transfer to prevent a situation where the token owner can't accept the // highest bid, because the bidder address does not implement IERC721Receiver. _transfer(seller, buyer, tokenId); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './Governance.sol'; /** * @title Provides permission check modifiers for child contracts */ abstract contract Governed { // Governance contract Governance public immutable governance; /** * @param governanceAddress Address of the Governance contract * * Requirements: * - Governance contract must be deployed at the given address */ constructor (address governanceAddress) { governance = Governance(governanceAddress); } /** * @dev Throws if given address that doesn't have ManagesDeaths permission * @param subject Address to check permissions for, usually msg.sender */ modifier canManageDeaths(address subject) { require( governance.hasPermission(subject, Governance.Actions.ManageDeaths), "Governance: subject is not allowed to manage deaths" ); _; } /** * @dev Throws if given address that doesn't have Configure permission * @param subject Address to check permissions for, usually msg.sender */ modifier canConfigure(address subject) { require( governance.hasPermission(subject, Governance.Actions.Configure), "Governance: subject is not allowed to configure contracts" ); _; } /** * @dev Throws if given address that doesn't have Bootstrap permission * @param subject Address to check permissions for, usually msg.sender */ modifier canBootstrap(address subject) { require( governance.hasPermission(subject, Governance.Actions.Bootstrap), "Governance: subject is not allowed to bootstrap" ); _; } /** * @dev Throws if given address that doesn't have SetOwnerAddress permission * @param subject Address to check permissions for, usually msg.sender */ modifier canSetOwnerAddress(address subject) { require( governance.hasPermission(subject, Governance.Actions.SetOwnerAddress), "Governance: subject is not allowed to set owner address" ); _; } /** * @dev Throws if given address that doesn't have TriggerOwnerWithdraw permission * @param subject Address to check permissions for, usually msg.sender */ modifier canTriggerOwnerWithdraw(address subject) { require( governance.hasPermission(subject, Governance.Actions.TriggerOwnerWithdraw), "Governance: subject is not allowed to trigger owner withdraw" ); _; } /** * @dev Throws if given address that doesn't have StopPayouyts permission * @param subject Address to check permissions for, usually msg.sender */ modifier canStopPayouts(address subject) { require( governance.hasPermission(subject, Governance.Actions.StopPayouts), "Governance: subject is not allowed to stop payouts" ); _; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; /** * @title Manages address permissions to act on Macabris contracts */ contract Governance { enum Actions { Vote, Configure, SetOwnerAddress, TriggerOwnerWithdraw, ManageDeaths, StopPayouts, Bootstrap } // Stores permissions of an address struct Permissions { bool canVote; bool canConfigure; bool canSetOwnerAddress; bool canTriggerOwnerWithdraw; bool canManageDeaths; bool canStopPayouts; // Special permission that can't be voted in and only the deploying address receives bool canBootstrap; } // A call for vote to change address permissions struct CallForVote { // Address that will be assigned the permissions if the vote passes address subject; // Permissions to be assigned if the vote passes Permissions permissions; // Total number of votes for and against the permission change uint128 yeas; uint128 nays; } // A vote in a call for vote struct Vote { uint64 callForVoteIndex; bool yeaOrNay; } // Permissions of addresses mapping(address => Permissions) private permissions; // List of calls for a vote: callForVoteIndex => CallForVote, callForVoteIndex starts from 1 mapping(uint => CallForVote) private callsForVote; // Last registered call for vote of every address: address => callForVoteIndex mapping(address => uint64) private lastRegisteredCallForVote; // Votes of every address: address => Vote mapping(address => Vote) private votes; uint64 public resolvedCallsForVote; uint64 public totalCallsForVote; uint64 public totalVoters; /** * @dev Emitted when a new call for vote is registered * @param callForVoteIndex Index of the call for vote (1-based) * @param subject Subject address to change permissions to if vote passes * @param canVote Allow subject address to vote * @param canConfigure Allow subject address to configure prices, fees and base URI * @param canSetOwnerAddress Allows subject to change owner withdraw address * @param canTriggerOwnerWithdraw Allow subject address to trigger withdraw from owner's balance * @param canManageDeaths Allow subject to set tokens as dead or alive * @param canStopPayouts Allow subject to stop the bank payout schedule early */ event CallForVoteRegistered( uint64 indexed callForVoteIndex, address indexed caller, address indexed subject, bool canVote, bool canConfigure, bool canSetOwnerAddress, bool canTriggerOwnerWithdraw, bool canManageDeaths, bool canStopPayouts ); /** * @dev Emitted when a call for vote is resolved * @param callForVoteIndex Index of the call for vote (1-based) * @param yeas Total yeas for the call after the vote * @param nays Total nays for the call after the vote */ event CallForVoteResolved( uint64 indexed callForVoteIndex, uint128 yeas, uint128 nays ); /** * @dev Emitted when a vote is casted * @param callForVoteIndex Index of the call for vote (1-based) * @param voter Voter address * @param yeaOrNay Vote, true if yea, false if nay * @param totalVoters Total addresses with vote permission at the time of event * @param yeas Total yeas for the call after the vote * @param nays Total nays for the call after the vote */ event VoteCasted( uint64 indexed callForVoteIndex, address indexed voter, bool yeaOrNay, uint64 totalVoters, uint128 yeas, uint128 nays ); /** * @dev Inits the contract and gives the deployer address all permissions */ constructor() { _setPermissions(msg.sender, Permissions({ canVote: true, canConfigure: true, canSetOwnerAddress: true, canTriggerOwnerWithdraw: true, canManageDeaths: true, canStopPayouts: true, canBootstrap: true })); } /** * @dev Checks if the given address has permission to perform given action * @param subject Address to check * @param action Action to check permissions against * @return True if given address has permission to perform given action */ function hasPermission(address subject, Actions action) public view returns (bool) { if (action == Actions.ManageDeaths) { return permissions[subject].canManageDeaths; } if (action == Actions.Vote) { return permissions[subject].canVote; } if (action == Actions.SetOwnerAddress) { return permissions[subject].canSetOwnerAddress; } if (action == Actions.TriggerOwnerWithdraw) { return permissions[subject].canTriggerOwnerWithdraw; } if (action == Actions.Configure) { return permissions[subject].canConfigure; } if (action == Actions.StopPayouts) { return permissions[subject].canStopPayouts; } if (action == Actions.Bootstrap) { return permissions[subject].canBootstrap; } return false; } /** * Sets permissions for a given address * @param subject Subject address to set permissions to * @param _permissions Permissions */ function _setPermissions(address subject, Permissions memory _permissions) private { // Tracks count of total voting addresses to be able to calculate majority if (permissions[subject].canVote != _permissions.canVote) { if (_permissions.canVote) { totalVoters += 1; } else { totalVoters -= 1; // Cleaning up voting-related state for the address delete votes[subject]; delete lastRegisteredCallForVote[subject]; } } permissions[subject] = _permissions; } /** * @dev Registers a new call for vote to change address permissions * @param subject Subject address to change permissions to if vote passes * @param canVote Allow subject address to vote * @param canConfigure Allow subject address to configure prices, fees and base URI * @param canSetOwnerAddress Allows subject to change owner withdraw address * @param canTriggerOwnerWithdraw Allow subject address to trigger withdraw from owner's balance * @param canManageDeaths Allow subject to set tokens as dead or alive * @param canStopPayouts Allow subject to stop the bank payout schedule early * * Requirements: * - the caller must have the vote permission * - the caller shouldn't have any unresolved calls for vote */ function callForVote( address subject, bool canVote, bool canConfigure, bool canSetOwnerAddress, bool canTriggerOwnerWithdraw, bool canManageDeaths, bool canStopPayouts ) external { require( hasPermission(msg.sender, Actions.Vote), "Only addresses with vote permission can register a call for vote" ); // If the sender has previously created a call for vote that hasn't been resolved yet, // a second call for vote can't be registered. Prevents a denial of service attack, where // a minority of voters could flood the call for vote queue. require( lastRegisteredCallForVote[msg.sender] <= resolvedCallsForVote, "Only one active call for vote per address is allowed" ); totalCallsForVote++; lastRegisteredCallForVote[msg.sender] = totalCallsForVote; callsForVote[totalCallsForVote] = CallForVote({ subject: subject, permissions: Permissions({ canVote: canVote, canConfigure: canConfigure, canSetOwnerAddress: canSetOwnerAddress, canTriggerOwnerWithdraw: canTriggerOwnerWithdraw, canManageDeaths: canManageDeaths, canStopPayouts: canStopPayouts, canBootstrap: false }), yeas: 0, nays: 0 }); emit CallForVoteRegistered( totalCallsForVote, msg.sender, subject, canVote, canConfigure, canSetOwnerAddress, canTriggerOwnerWithdraw, canManageDeaths, canStopPayouts ); } /** * @dev Registers a vote * @param callForVoteIndex Call for vote index * @param yeaOrNay True to vote yea, false to vote nay * * Requirements: * - unresolved call for vote must exist * - call for vote index must match the current active call for vote * - the caller must have the vote permission */ function vote(uint64 callForVoteIndex, bool yeaOrNay) external { require(hasUnresolvedCallForVote(), "No unresolved call for vote exists"); require( callForVoteIndex == _getCurrenCallForVoteIndex(), "Call for vote does not exist or is not active" ); require( hasPermission(msg.sender, Actions.Vote), "Sender address does not have vote permission" ); uint128 yeas = callsForVote[callForVoteIndex].yeas; uint128 nays = callsForVote[callForVoteIndex].nays; // If the voter has already voted in this call for vote, undo the last vote if (votes[msg.sender].callForVoteIndex == callForVoteIndex) { if (votes[msg.sender].yeaOrNay) { yeas -= 1; } else { nays -= 1; } } if (yeaOrNay) { yeas += 1; } else { nays += 1; } emit VoteCasted(callForVoteIndex, msg.sender, yeaOrNay, totalVoters, yeas, nays); if (yeas == (totalVoters / 2 + 1) || nays == (totalVoters - totalVoters / 2)) { if (yeas > nays) { _setPermissions( callsForVote[callForVoteIndex].subject, callsForVote[callForVoteIndex].permissions ); } resolvedCallsForVote += 1; // Cleaning up what we can delete callsForVote[callForVoteIndex]; delete votes[msg.sender]; emit CallForVoteResolved(callForVoteIndex, yeas, nays); return; } votes[msg.sender] = Vote({ callForVoteIndex: callForVoteIndex, yeaOrNay: yeaOrNay }); callsForVote[callForVoteIndex].yeas = yeas; callsForVote[callForVoteIndex].nays = nays; } /** * @dev Returns information about the current unresolved call for vote * @return callForVoteIndex Call for vote index (1-based) * @return yeas Total yea votes * @return nays Total nay votes * * Requirements: * - Unresolved call for vote must exist */ function getCurrentCallForVote() public view returns ( uint64 callForVoteIndex, uint128 yeas, uint128 nays ) { require(hasUnresolvedCallForVote(), "No unresolved call for vote exists"); uint64 index = _getCurrenCallForVoteIndex(); return (index, callsForVote[index].yeas, callsForVote[index].nays); } /** * @dev Checks if there is an unresolved call for vote * @return True if an unresolved call for vote exists */ function hasUnresolvedCallForVote() public view returns (bool) { return totalCallsForVote > resolvedCallsForVote; } /** * @dev Returns current call for vote index * @return Call for vote index (1-based) * * Doesn't check if an unresolved call for vote exists, hasUnresolvedCallForVote should be used * before using the index that this method returns. */ function _getCurrenCallForVoteIndex() private view returns (uint64) { return resolvedCallsForVote + 1; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './Governed.sol'; import './OwnerBalanceContributor.sol'; import './Macabris.sol'; import './Reaper.sol'; /** * @title Contract tracking payouts to token owners according to predefined schedule * * Payout schedule is dived into intervalCount intervals of intervalLength durations, starting at * startTime timestamp. After each interval, part of the payouts pool is distributed to the owners * of the tokens that are still alive. After the whole payout schedule is completed, all the funds * in the payout pool will have been distributed. * * There is a possibility of the payout schedule being stopped early. In that case, all of the * remaining funds will be distributed to the owners of the tokens that were alive at the time of * the payout schedule stop. */ contract Bank is Governed, OwnerBalanceContributor { // Macabris NFT contract Macabris public macabris; // Reaper contract Reaper public reaper; // Stores active token count change and deposits for an interval struct IntervalActivity { int128 activeTokenChange; uint128 deposits; } // Stores aggregate interval information struct IntervalTotals { uint index; uint deposits; uint payouts; uint accountPayouts; uint activeTokens; uint accountActiveTokens; } // The same as IntervalTotals, but a packed version to keep in the lastWithdrawTotals map. // Packed versions costs less to store, but the math is then more expensive duo to type // conversions, so the interval data is packed just before storing, and unpacked after loading. struct IntervalTotalsPacked { uint128 deposits; uint128 payouts; uint128 accountPayouts; uint48 activeTokens; uint48 accountActiveTokens; uint32 index; } // Timestamp of when the first interval starts uint64 public immutable startTime; // Timestamp of the moment the payouts have been stopped and the bank contents distributed. // This should remain 0, if the payout schedule is never stopped manually. uint64 public stopTime; // Total number of intervals uint64 public immutable intervalCount; // Interval length in seconds uint64 public immutable intervalLength; // Activity for each interval mapping(uint => IntervalActivity) private intervals; // Active token change for every interval for every address individually mapping(uint => mapping(address => int)) private individualIntervals; // Total withdrawn amount fo each address mapping(address => uint) private withdrawals; // Totals of the interval before the last withdrawal of an address mapping(address => IntervalTotalsPacked) private lastWithdrawTotals; /** * @param _startTime First interval start unix timestamp * @param _intervalCount Interval count * @param _intervalLength Interval length in seconds * @param governanceAddress Address of the Governance contract * @param ownerBalanceAddress Address of the OwnerBalance contract * * Requirements: * - interval length must be at least one second (but should be more like a month) * - interval count must be bigger than zero * - Governance contract must be deployed at the given address * - OwnerBalance contract must be deployed at the given address */ constructor( uint64 _startTime, uint64 _intervalCount, uint64 _intervalLength, address governanceAddress, address ownerBalanceAddress ) Governed(governanceAddress) OwnerBalanceContributor(ownerBalanceAddress) { require(_intervalLength > 0, "Interval length can't be zero"); require(_intervalCount > 0, "At least one interval is required"); startTime = _startTime; intervalCount = _intervalCount; intervalLength = _intervalLength; } /** * @dev Sets Macabris NFT contract address * @param macabrisAddress Address of Macabris NFT contract * * Requirements: * - the caller must have the bootstrap permission * - Macabris contract must be deployed at the given address */ function setMacabrisAddress(address macabrisAddress) external canBootstrap(msg.sender) { macabris = Macabris(macabrisAddress); } /** * @dev Sets Reaper contract address * @param reaperAddress Address of Reaper contract * * Requirements: * - the caller must have the bootstrap permission * - Reaper contract must be deployed at the given address */ function setReaperAddress(address reaperAddress) external canBootstrap(msg.sender) { reaper = Reaper(reaperAddress); } /** * @dev Stops payouts, distributes remaining funds among alive tokens * * Requirements: * - the caller must have the stop payments permission * - the payout schedule must not have been stopped previously * - the payout schedule should not be completed */ function stopPayouts() external canStopPayouts(msg.sender) { require(stopTime == 0, "Payouts are already stopped"); require(block.timestamp < getEndTime(), "Payout schedule is already completed"); stopTime = uint64(block.timestamp); } /** * @dev Checks if the payouts are finished or have been stopped manually * @return True if finished or stopped */ function hasEnded() public view returns (bool) { return stopTime > 0 || block.timestamp >= getEndTime(); } /** * @dev Returns timestamp of the first second after the last interval * @return Unix timestamp */ function getEndTime() public view returns(uint) { return _getIntervalStartTime(intervalCount); } /** * @dev Returns a timestamp of the first second of the given interval * @return Unix timestamp * * Doesn't make any bound checks for the given interval! */ function _getIntervalStartTime(uint interval) private view returns(uint) { return startTime + interval * intervalLength; } /** * @dev Returns start time of the upcoming interval * @return Unix timestamp */ function getNextIntervalStartTime() public view returns (uint) { // If the payouts were ended manually, there will be no next interval if (stopTime > 0) { return 0; } // Returns first intervals start time if the payout schedule hasn't started yet if (block.timestamp < startTime) { return startTime; } uint currentInterval = _getInterval(block.timestamp); // There will be no intervals after the last one, return 0 if (currentInterval >= (intervalCount - 1)) { return 0; } // Returns next interval's start time otherwise return _getIntervalStartTime(currentInterval + 1); } /** * @dev Deposits ether to the common payout pool */ function deposit() external payable { // If the payouts have ended, we don't need to track deposits anymore, everything goes to // the owner's balance if (hasEnded()) { _transferToOwnerBalance(msg.value); return; } require(msg.value <= type(uint128).max, "Deposits bigger than uint128 max value are not allowed!"); uint currentInterval = _getInterval(block.timestamp); intervals[currentInterval].deposits += uint128(msg.value); } /** * @dev Registers token transfer, minting and burning * @param tokenId Token ID * @param from Previous token owner, zero if this is a freshly minted token * @param to New token owner, zero if the token is being burned * * Requirements: * - the caller must be the Macabris contract */ function onTokenTransfer(uint tokenId, address from, address to) external { require(msg.sender == address(macabris), "Caller must be the Macabris contract"); // If the payouts have ended, we don't need to track transfers anymore if (hasEnded()) { return; } // If token is already dead, nothing changes in terms of payouts if (reaper.getTimeOfDeath(tokenId) != 0) { return; } uint currentInterval = _getInterval(block.timestamp); if (from == address(0)) { // If the token is freshly minted, increase the total active token count for the period intervals[currentInterval].activeTokenChange += 1; } else { // If the token is transfered, decrease the previous ownner's total for the current interval individualIntervals[currentInterval][from] -= 1; } if (to == address(0)) { // If the token is burned, decrease the total active token count for the period intervals[currentInterval].activeTokenChange -= 1; } else { // If the token is transfered, add it to the receiver's total for the current interval individualIntervals[currentInterval][to] += 1; } } /** * @dev Registers token death * @param tokenId Token ID * * Requirements: * - the caller must be the Reaper contract */ function onTokenDeath(uint tokenId) external { require(msg.sender == address(reaper), "Caller must be the Reaper contract"); // If the payouts have ended, we don't need to track deaths anymore if (hasEnded()) { return; } // If the token isn't minted yet, we don't care about it if (!macabris.exists(tokenId)) { return; } uint currentInterval = _getInterval(block.timestamp); address owner = macabris.ownerOf(tokenId); intervals[currentInterval].activeTokenChange -= 1; individualIntervals[currentInterval][owner] -= 1; } /** * @dev Registers token resurrection * @param tokenId Token ID * * Requirements: * - the caller must be the Reaper contract */ function onTokenResurrection(uint tokenId) external { require(msg.sender == address(reaper), "Caller must be the Reaper contract"); // If the payouts have ended, we don't need to track deaths anymore if (hasEnded()) { return; } // If the token isn't minted yet, we don't care about it if (!macabris.exists(tokenId)) { return; } uint currentInterval = _getInterval(block.timestamp); address owner = macabris.ownerOf(tokenId); intervals[currentInterval].activeTokenChange += 1; individualIntervals[currentInterval][owner] += 1; } /** * Returns current interval index * @return Interval index (0 for the first interval, intervalCount-1 for the last) * * Notes: * - Returns zero (first interval), if the first interval hasn't started yet * - Returns the interval at the stop time, if the payouts have been stopped * - Returns "virtual" interval after the last one, if the payout schedule is completed */ function _getCurrentInterval() private view returns(uint) { // If the payouts have been stopped, return interval after the stopped one if (stopTime > 0) { return _getInterval(stopTime); } uint intervalIndex = _getInterval(block.timestamp); // Return "virtual" interval that would come after the last one, if payout schedule is completed if (intervalIndex > intervalCount) { return intervalCount; } return intervalIndex; } /** * Returns interval index for the given timestamp * @return Interval index (0 for the first interval, intervalCount-1 for the last) * * Notes: * - Returns zero (first interval), if the first interval hasn't started yet * - Returns non-exitent interval index, if the timestamp is after the end time */ function _getInterval(uint timestamp) private view returns(uint) { // Time before the payout schedule start is considered to be a part of the first interval if (timestamp < startTime) { return 0; } return (timestamp - startTime) / intervalLength; } /** * @dev Returns total pool value (deposits - payouts) for the current interval * @return Current pool value in wei */ function getPoolValue() public view returns (uint) { // If all the payouts are done, pool is empty. In reality, there might something left due to // last interval pool not dividing equaly between the remaining alive tokens, or if there // are no alive tokens during the last interval. if (hasEnded()) { return 0; } uint currentInterval = _getInterval(block.timestamp); IntervalTotals memory totals = _getIntervalTotals(currentInterval, address(0)); return totals.deposits - totals.payouts; } /** * @dev Returns provisional next payout value per active token of the current interval * @return Payout in wei, zero if no active tokens exist or all payouts are done */ function getNextPayout() external view returns (uint) { // There is no next payout if the payout schedule has run its course if (hasEnded()) { return 0; } uint currentInterval = _getInterval(block.timestamp); IntervalTotals memory totals = _getIntervalTotals(currentInterval, address(0)); return _getPayoutPerToken(totals); } /** * @dev Returns payout amount per token for the given interval * @param totals Interval totals * @return Payout value in wei * * Notes: * - Returns zero for the "virtual" interval after the payout schedule end * - Returns zero if no active tokens exists for the interval */ function _getPayoutPerToken(IntervalTotals memory totals) private view returns (uint) { // If we're calculating next payout for the "virtual" interval after the last one, // or if there are no active tokens, we would be dividing the pool by zero if (totals.activeTokens > 0 && totals.index < intervalCount) { return (totals.deposits - totals.payouts) / (intervalCount - totals.index) / totals.activeTokens; } else { return 0; } } /** * @dev Returns the sum of all payouts made up until this interval * @return Payouts total in wei */ function getPayoutsTotal() external view returns (uint) { uint interval = _getCurrentInterval(); IntervalTotals memory totals = _getIntervalTotals(interval, address(0)); uint payouts = totals.payouts; // If the payout schedule has been stopped prematurely, all deposits are distributed. // If there are no active tokens, the remainder of the pool is never distributed. if (stopTime > 0 && totals.activeTokens > 0) { // Remaining pool might not divide equally between the active tokens, calculating // distributed amount without the remainder payouts += (totals.deposits - totals.payouts) / totals.activeTokens * totals.activeTokens; } return payouts; } /** * @dev Returns the sum of payouts for a particular account * @param account Account address * @return Payouts total in wei */ function getAccountPayouts(address account) public view returns (uint) { uint interval = _getCurrentInterval(); IntervalTotals memory totals = _getIntervalTotals(interval, account); uint accountPayouts = totals.accountPayouts; // If the payout schedule has been stopped prematurely, all deposits are distributed. // If there are no active tokens, the remainder of the pool is never distributed. if (stopTime > 0 && totals.activeTokens > 0) { accountPayouts += (totals.deposits - totals.payouts) / totals.activeTokens * totals.accountActiveTokens; } return accountPayouts; } /** * @dev Returns amount available for withdrawal * @param account Address to return balance for * @return Amount int wei */ function getBalance(address account) public view returns (uint) { return getAccountPayouts(account) - withdrawals[account]; } /** * @dev Withdraws all available amount * @param account Address to withdraw for * * Note that this method can be called by any address. */ function withdraw(address payable account) external { uint interval = _getCurrentInterval(); // Persists last finished interval totals to avoid having to recalculate them from the // deltas during the next withdrawal. Totals of the first interval should never be saved // to the lastWithdrawTotals map (see _getIntervalTotals for explanation). if (interval > 1) { IntervalTotals memory totals = _getIntervalTotals(interval - 1, account); // Converting the totals struct to a packed version before saving to storage to save gas lastWithdrawTotals[account] = IntervalTotalsPacked({ deposits: uint128(totals.deposits), payouts: uint128(totals.payouts), accountPayouts: uint128(totals.accountPayouts), activeTokens: uint48(totals.activeTokens), accountActiveTokens: uint48(totals.accountActiveTokens), index: uint32(totals.index) }); } uint balance = getBalance(account); withdrawals[account] += balance; account.transfer(balance); } /** * @dev Aggregates active token and deposit change history until the given interval * @param intervalIndex Interval * @param account Account for account-specific aggregate values * @return Aggregate values for the interval */ function _getIntervalTotals(uint intervalIndex, address account) private view returns (IntervalTotals memory) { IntervalTotalsPacked storage packed = lastWithdrawTotals[account]; // Converting packed totals struct back to unpacked one, to avoid having to do type // conversions in the loop below. IntervalTotals memory totals = IntervalTotals({ index: packed.index, deposits: packed.deposits, payouts: packed.payouts, accountPayouts: packed.accountPayouts, activeTokens: packed.activeTokens, accountActiveTokens: packed.accountActiveTokens }); uint prevPayout; uint prevAccountPayout; uint prevPayoutPerToken; // If we don't have previous totals, we need to start from intervalIndex 0 to apply the // active token and deposit changes of the first interval. If we have previous totals, they // the include all the activity of the interval already, so we start from the next one. // // Note that it's assumed all the interval total values will be 0, if the totals.index is 0. // This means that the totals of the first interval should never be saved to the // lastWithdrawTotals maps otherwise the deposits and active token changes will be counted twice. for (uint i = totals.index > 0 ? totals.index + 1 : 0; i <= intervalIndex; i++) { // Calculating payouts for the last interval data. If this is the first interval and // there was no previous interval totals, all these values will resolve to 0. prevPayoutPerToken = _getPayoutPerToken(totals); prevPayout = prevPayoutPerToken * totals.activeTokens; prevAccountPayout = totals.accountActiveTokens * prevPayoutPerToken; // Updating totals to represent the current interval by adding the payouts of the last // interval and applying changes in active token count and deposits totals.index = i; totals.payouts += prevPayout; totals.accountPayouts += prevAccountPayout; IntervalActivity storage interval = intervals[i]; totals.deposits += interval.deposits; // Even though the token change value might be negative, the sum of all the changes // will never be negative because of the implicit contrains of the contracts (e.g. token // can't be transfered from an address that does not own it, or already dead token can't // be marked dead again). Therefore it's safe to convert the result into unsigned value, // after doing sum of signed values. totals.activeTokens = uint(int(totals.activeTokens) + interval.activeTokenChange); totals.accountActiveTokens = uint(int(totals.accountActiveTokens) + individualIntervals[i][account]); } return totals; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../access/Ownable.sol"; import "../Address.sol"; /** * @title Escrow * @dev Base escrow contract, holds funds designated for a payee until they * withdraw them. * * Intended usage: This contract (and derived escrow contracts) should be a * standalone contract, that only interacts with the contract that instantiated * it. That way, it is guaranteed that all Ether will be handled according to * the `Escrow` rules, and there is no need to check for payable functions or * transfers in the inheritance tree. The contract that uses the escrow as its * payment method should be its owner, and provide public methods redirecting * to the escrow's deposit and withdraw. */ contract Escrow is Ownable { using Address for address payable; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private _deposits; function depositsOf(address payee) public view returns (uint256) { return _deposits[payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param payee The destination address of the funds. */ function deposit(address payee) public payable virtual onlyOwner { uint256 amount = msg.value; _deposits[payee] += amount; emit Deposited(payee, amount); } /** * @dev Withdraw accumulated balance for a payee, forwarding all gas to the * recipient. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address payable payee) public virtual onlyOwner { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.sendValue(payment); emit Withdrawn(payee, payment); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/escrow/Escrow.sol"; /** * @dev Simple implementation of a * https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment] * strategy, where the paying contract doesn't interact directly with the * receiver account, which must withdraw its payments itself. * * Pull-payments are often considered the best practice when it comes to sending * Ether, security-wise. It prevents recipients from blocking execution, and * eliminates reentrancy concerns. * * 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]. * * To use, derive from the `PullPayment` contract, and use {_asyncTransfer} * instead of Solidity's `transfer` function. Payees can query their due * payments with {payments}, and retrieve them with {withdrawPayments}. */ abstract contract PullPayment { Escrow private immutable _escrow; constructor() { _escrow = new Escrow(); } /** * @dev Withdraw accumulated payments, forwarding all gas to the recipient. * * Note that _any_ account can call this function, not just the `payee`. * This means that contracts unaware of the `PullPayment` protocol can still * receive funds this way, by having a separate account call * {withdrawPayments}. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee Whose payments will be withdrawn. */ function withdrawPayments(address payable payee) public virtual { _escrow.withdraw(payee); } /** * @dev Returns the payments owed to an address. * @param dest The creditor's address. */ function payments(address dest) public view returns (uint256) { return _escrow.depositsOf(dest); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * Funds sent in this way are stored in an intermediate {Escrow} contract, so * there is no danger of them being spent before withdrawal. * * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function _asyncTransfer(address dest, uint256 amount) internal virtual { _escrow.deposit{value: amount}(dest); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
Calculates fee amount based on given price and fee in bps price Price base for calculation fee Fee in basis points return Fee amount in wei/ Fee might be zero, avoiding division by zero
function _calculateFeeAmount(uint price, uint fee) private pure returns (uint) { if (fee == 0) { return 0; } }
10,435,029
./partial_match/1/0x04490df348A337D275feCB4fE43DD90f4a7b64c9/sources/CreaticlesNFT.sol
MUTABLE FUNCTIONS creates a request _detailsHash => keccak256 hash of the metadata of the request _numberOfWinners => the initially set number of winners. A request cannot take more winners than specified _duration => time span of contest in seconds. After this time is up. No more proposals can be taken and the choosing period starts _numMintPerToken => number of NFTs per winner . You can choose to mint fewer NFTs when your contest is over but you cannot mint more. _paymentERC20Address => ERC20Address of payment _paymentValue => Value of payment/ zero address corresponds to ethereum payment, the default Here we explore additional ERC20 payment options
function createRequest( bytes32 _detailsHash, uint16 _numberOfWinners, uint32 _duration, uint256 _numMintPerToken, address _paymentERC20Address, uint256 _paymentValue ) public payable returns (uint256) { require(_numberOfWinners > 0); require(_paymentValue > 0); uint256 _cval; uint256 _value; { if (_paymentERC20Address == address(0)) { require(msg.value == _paymentValue); _value = msg.value - _cval; treasury.transfer(_cval); IERC20(_paymentERC20Address).transferFrom( msg.sender, address(this), _paymentValue ); _value = _paymentValue - _cval; IERC20(_paymentERC20Address).transfer(treasury, _cval); } request_erc20_addresses[numberOfRequests] = _paymentERC20Address; Request storage _request = requests[numberOfRequests]; _request.requester = msg.sender; _request.detailsHash = _detailsHash; _request.value = _value; _request.numberOfWinners = _numberOfWinners; _request.createdAt = block.timestamp; _request.expiresAt = block.timestamp + _duration; _request.active = true; _request.numMintPerToken = _numMintPerToken; numberOfRequests += 1; } emit RequestCreated( numberOfRequests - 1, msg.sender, _detailsHash, _value, _numberOfWinners, block.timestamp, block.timestamp + _duration, true, _numMintPerToken ); return numberOfRequests - 1; }
4,413,156
./partial_match/1/0xDF7F126B7270BA17C7b9964188e9020EB410096d/sources/PepemonStake.sol
Returns the % progress of the user towards completion of the event (100% = 1e5)
function getUserProgress(address _user, uint256 _eventId) external view returns(uint256) { StakingEvent memory _event = stakingEvents[_eventId]; UserInfo memory _userInfo = userInfo[_user][_eventId]; if (_userInfo.blockEnd == 0) { return 0; } if (_userInfo.isCompleted || block.number >= _userInfo.blockEnd) { return 1e5; } uint256 blocksLeft = _userInfo.blockEnd.sub(block.number); return blocksStaked.mul(1e5).div(_event.blockStakeLength); }
3,633,137
pragma solidity 0.5.17; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "../interfaces/Comptroller.sol"; import "../interfaces/PriceOracle.sol"; import "../interfaces/CERC20.sol"; import "../interfaces/CEther.sol"; import "../Utils.sol"; contract CompoundOrder is Utils(address(0), address(0), address(0)), Ownable { // Constants uint256 internal constant NEGLIGIBLE_DEBT = 100; // we don't care about debts below 10^-4 USDC (0.1 cent) uint256 internal constant MAX_REPAY_STEPS = 3; // Max number of times we attempt to repay remaining debt uint256 internal constant DEFAULT_LIQUIDITY_SLIPPAGE = 10 ** 12; // 1e-6 slippage for redeeming liquidity when selling order uint256 internal constant FALLBACK_LIQUIDITY_SLIPPAGE = 10 ** 15; // 0.1% slippage for redeeming liquidity when selling order uint256 internal constant MAX_LIQUIDITY_SLIPPAGE = 10 ** 17; // 10% max slippage for redeeming liquidity when selling order // Contract instances Comptroller public COMPTROLLER; // The Compound comptroller PriceOracle public ORACLE; // The Compound price oracle CERC20 public CUSDC; // The Compound USDC market token address public CETH_ADDR; // Instance variables uint256 public stake; uint256 public collateralAmountInUSDC; uint256 public loanAmountInUSDC; uint256 public cycleNumber; uint256 public buyTime; // Timestamp for order execution uint256 public outputAmount; // Records the total output USDC after order is sold address public compoundTokenAddr; bool public isSold; bool public orderType; // True for shorting, false for longing bool internal initialized; constructor() public {} function init( address _compoundTokenAddr, uint256 _cycleNumber, uint256 _stake, uint256 _collateralAmountInUSDC, uint256 _loanAmountInUSDC, bool _orderType, address _usdcAddr, address payable _kyberAddr, address _comptrollerAddr, address _priceOracleAddr, address _cUSDCAddr, address _cETHAddr ) public { require(!initialized); initialized = true; // Initialize details of order require(_compoundTokenAddr != _cUSDCAddr); require(_stake > 0 && _collateralAmountInUSDC > 0 && _loanAmountInUSDC > 0); // Validate inputs stake = _stake; collateralAmountInUSDC = _collateralAmountInUSDC; loanAmountInUSDC = _loanAmountInUSDC; cycleNumber = _cycleNumber; compoundTokenAddr = _compoundTokenAddr; orderType = _orderType; COMPTROLLER = Comptroller(_comptrollerAddr); ORACLE = PriceOracle(_priceOracleAddr); CUSDC = CERC20(_cUSDCAddr); CETH_ADDR = _cETHAddr; USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; usdc = ERC20Detailed(_usdcAddr); kyber = KyberNetwork(_kyberAddr); // transfer ownership to msg.sender _transferOwnership(msg.sender); } /** * @notice Executes the Compound order * @param _minPrice the minimum token price * @param _maxPrice the maximum token price */ function executeOrder(uint256 _minPrice, uint256 _maxPrice) public; /** * @notice Sells the Compound order and returns assets to PeakDeFiFund * @param _minPrice the minimum token price * @param _maxPrice the maximum token price */ function sellOrder(uint256 _minPrice, uint256 _maxPrice) public returns (uint256 _inputAmount, uint256 _outputAmount); /** * @notice Repays the loans taken out to prevent the collateral ratio from dropping below threshold * @param _repayAmountInUSDC the amount to repay, in USDC */ function repayLoan(uint256 _repayAmountInUSDC) public; /** * @notice Emergency method, which allow to transfer selected tokens to the fund address * @param _tokenAddr address of withdrawn token * @param _receiver address who should receive tokens */ function emergencyExitTokens(address _tokenAddr, address _receiver) public onlyOwner { ERC20Detailed token = ERC20Detailed(_tokenAddr); token.safeTransfer(_receiver, token.balanceOf(address(this))); } function getMarketCollateralFactor() public view returns (uint256); function getCurrentCollateralInUSDC() public returns (uint256 _amount); function getCurrentBorrowInUSDC() public returns (uint256 _amount); function getCurrentCashInUSDC() public view returns (uint256 _amount); /** * @notice Calculates the current profit in USDC * @return the profit amount */ function getCurrentProfitInUSDC() public returns (bool _isNegative, uint256 _amount) { uint256 l; uint256 r; if (isSold) { l = outputAmount; r = collateralAmountInUSDC; } else { uint256 cash = getCurrentCashInUSDC(); uint256 supply = getCurrentCollateralInUSDC(); uint256 borrow = getCurrentBorrowInUSDC(); if (cash >= borrow) { l = supply.add(cash); r = borrow.add(collateralAmountInUSDC); } else { l = supply; r = borrow.sub(cash).mul(PRECISION).div(getMarketCollateralFactor()).add(collateralAmountInUSDC); } } if (l >= r) { return (false, l.sub(r)); } else { return (true, r.sub(l)); } } /** * @notice Calculates the current collateral ratio on Compound, using 18 decimals * @return the collateral ratio */ function getCurrentCollateralRatioInUSDC() public returns (uint256 _amount) { uint256 supply = getCurrentCollateralInUSDC(); uint256 borrow = getCurrentBorrowInUSDC(); if (borrow == 0) { return uint256(-1); } return supply.mul(PRECISION).div(borrow); } /** * @notice Calculates the current liquidity (supply - collateral) on the Compound platform * @return the liquidity */ function getCurrentLiquidityInUSDC() public returns (bool _isNegative, uint256 _amount) { uint256 supply = getCurrentCollateralInUSDC(); uint256 borrow = getCurrentBorrowInUSDC().mul(PRECISION).div(getMarketCollateralFactor()); if (supply >= borrow) { return (false, supply.sub(borrow)); } else { return (true, borrow.sub(supply)); } } function __sellUSDCForToken(uint256 _usdcAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) { ERC20Detailed t = __underlyingToken(compoundTokenAddr); (,, _actualTokenAmount, _actualUSDCAmount) = __kyberTrade(usdc, _usdcAmount, t); // Sell USDC for tokens on Kyber require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values } function __sellTokenForUSDC(uint256 _tokenAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) { ERC20Detailed t = __underlyingToken(compoundTokenAddr); (,, _actualUSDCAmount, _actualTokenAmount) = __kyberTrade(t, _tokenAmount, usdc); // Sell tokens for USDC on Kyber require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values } // Convert a USDC amount to the amount of a given token that's of equal value function __usdcToToken(address _cToken, uint256 _usdcAmount) internal view returns (uint256) { ERC20Detailed t = __underlyingToken(_cToken); return _usdcAmount.mul(PRECISION).div(10 ** getDecimals(usdc)).mul(10 ** getDecimals(t)).div(ORACLE.getUnderlyingPrice(_cToken).mul(10 ** getDecimals(t)).div(PRECISION)); } // Convert a compound token amount to the amount of USDC that's of equal value function __tokenToUSDC(address _cToken, uint256 _tokenAmount) internal view returns (uint256) { return _tokenAmount.mul(ORACLE.getUnderlyingPrice(_cToken)).div(PRECISION).mul(10 ** getDecimals(usdc)).div(PRECISION); } function __underlyingToken(address _cToken) internal view returns (ERC20Detailed) { if (_cToken == CETH_ADDR) { // ETH return ETH_TOKEN_ADDRESS; } CERC20 ct = CERC20(_cToken); address underlyingToken = ct.underlying(); ERC20Detailed t = ERC20Detailed(underlyingToken); return t; } function() external payable {} } pragma solidity ^0.5.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity 0.5.17; // Compound finance comptroller interface Comptroller { function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function markets(address cToken) external view returns (bool isListed, uint256 collateralFactorMantissa); } pragma solidity 0.5.17; // Compound finance's price oracle interface PriceOracle { // returns the price of the underlying token in USD, scaled by 10**(36 - underlyingPrecision) function getUnderlyingPrice(address cToken) external view returns (uint); } pragma solidity 0.5.17; // Compound finance ERC20 market interface interface CERC20 { function mint(uint mintAmount) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function exchangeRateCurrent() external returns (uint); function balanceOf(address account) external view returns (uint); function decimals() external view returns (uint); function underlying() external view returns (address); } pragma solidity 0.5.17; // Compound finance Ether market interface interface CEther { function mint() external payable; function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow() external payable; function borrowBalanceCurrent(address account) external returns (uint); function exchangeRateCurrent() external returns (uint); function balanceOf(address account) external view returns (uint); function decimals() external view returns (uint); } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/KyberNetwork.sol"; import "./interfaces/OneInchExchange.sol"; /** * @title The smart contract for useful utility functions and constants. * @author Zefram Lou (Zebang Liu) */ contract Utils { using SafeMath for uint256; using SafeERC20 for ERC20Detailed; /** * @notice Checks if `_token` is a valid token. * @param _token the token's address */ modifier isValidToken(address _token) { require(_token != address(0)); if (_token != address(ETH_TOKEN_ADDRESS)) { require(isContract(_token)); } _; } address public USDC_ADDR; address payable public KYBER_ADDR; address payable public ONEINCH_ADDR; bytes public constant PERM_HINT = "PERM"; // The address Kyber Network uses to represent Ether ERC20Detailed internal constant ETH_TOKEN_ADDRESS = ERC20Detailed(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); ERC20Detailed internal usdc; KyberNetwork internal kyber; uint256 constant internal PRECISION = (10**18); uint256 constant internal MAX_QTY = (10**28); // 10B tokens uint256 constant internal ETH_DECIMALS = 18; uint256 constant internal MAX_DECIMALS = 18; constructor( address _usdcAddr, address payable _kyberAddr, address payable _oneInchAddr ) public { USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; ONEINCH_ADDR = _oneInchAddr; usdc = ERC20Detailed(_usdcAddr); kyber = KyberNetwork(_kyberAddr); } /** * @notice Get the number of decimals of a token * @param _token the token to be queried * @return number of decimals */ function getDecimals(ERC20Detailed _token) internal view returns(uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(ETH_DECIMALS); } return uint256(_token.decimals()); } /** * @notice Get the token balance of an account * @param _token the token to be queried * @param _addr the account whose balance will be returned * @return token balance of the account */ function getBalance(ERC20Detailed _token, address _addr) internal view returns(uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(_addr.balance); } return uint256(_token.balanceOf(_addr)); } /** * @notice Calculates the rate of a trade. The rate is the price of the source token in the dest token, in 18 decimals. * Note: the rate is on the token level, not the wei level, so for example if 1 Atoken = 10 Btoken, then the rate * from A to B is 10 * 10**18, regardless of how many decimals each token uses. * @param srcAmount amount of source token * @param destAmount amount of dest token * @param srcDecimals decimals used by source token * @param dstDecimals decimals used by dest token */ function calcRateFromQty(uint256 srcAmount, uint256 destAmount, uint256 srcDecimals, uint256 dstDecimals) internal pure returns(uint) { require(srcAmount <= MAX_QTY); require(destAmount <= MAX_QTY); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount); } } /** * @notice Wrapper function for doing token conversion on Kyber Network * @param _srcToken the token to convert from * @param _srcAmount the amount of tokens to be converted * @param _destToken the destination token * @return _destPriceInSrc the price of the dest token, in terms of source tokens * _srcPriceInDest the price of the source token, in terms of dest tokens * _actualDestAmount actual amount of dest token traded * _actualSrcAmount actual amount of src token traded */ function __kyberTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken) internal returns( uint256 _destPriceInSrc, uint256 _srcPriceInDest, uint256 _actualDestAmount, uint256 _actualSrcAmount ) { require(_srcToken != _destToken); uint256 beforeSrcBalance = getBalance(_srcToken, address(this)); uint256 msgValue; if (_srcToken != ETH_TOKEN_ADDRESS) { msgValue = 0; _srcToken.safeApprove(KYBER_ADDR, 0); _srcToken.safeApprove(KYBER_ADDR, _srcAmount); } else { msgValue = _srcAmount; } _actualDestAmount = kyber.tradeWithHint.value(msgValue)( _srcToken, _srcAmount, _destToken, toPayableAddr(address(this)), MAX_QTY, 1, address(0), PERM_HINT ); _actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this))); require(_actualDestAmount > 0 && _actualSrcAmount > 0); _destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken)); _srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken)); } /** * @notice Wrapper function for doing token conversion on 1inch * @param _srcToken the token to convert from * @param _srcAmount the amount of tokens to be converted * @param _destToken the destination token * @return _destPriceInSrc the price of the dest token, in terms of source tokens * _srcPriceInDest the price of the source token, in terms of dest tokens * _actualDestAmount actual amount of dest token traded * _actualSrcAmount actual amount of src token traded */ function __oneInchTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken, bytes memory _calldata) internal returns( uint256 _destPriceInSrc, uint256 _srcPriceInDest, uint256 _actualDestAmount, uint256 _actualSrcAmount ) { require(_srcToken != _destToken); uint256 beforeSrcBalance = getBalance(_srcToken, address(this)); uint256 beforeDestBalance = getBalance(_destToken, address(this)); // Note: _actualSrcAmount is being used as msgValue here, because otherwise we'd run into the stack too deep error if (_srcToken != ETH_TOKEN_ADDRESS) { _actualSrcAmount = 0; OneInchExchange dex = OneInchExchange(ONEINCH_ADDR); address approvalHandler = dex.spender(); _srcToken.safeApprove(approvalHandler, 0); _srcToken.safeApprove(approvalHandler, _srcAmount); } else { _actualSrcAmount = _srcAmount; } // trade through 1inch proxy (bool success,) = ONEINCH_ADDR.call.value(_actualSrcAmount)(_calldata); require(success); // calculate trade amounts and price _actualDestAmount = getBalance(_destToken, address(this)).sub(beforeDestBalance); _actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this))); require(_actualDestAmount > 0 && _actualSrcAmount > 0); _destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken)); _srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken)); } /** * @notice Checks if an Ethereum account is a smart contract * @param _addr the account to be checked * @return True if the account is a smart contract, false otherwise */ function isContract(address _addr) internal view returns(bool) { uint256 size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size>0; } function toPayableAddr(address _addr) internal pure returns (address payable) { return address(uint160(_addr)); } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; /** * @title The interface for the Kyber Network smart contract * @author Zefram Lou (Zebang Liu) */ interface KyberNetwork { function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function tradeWithHint( ERC20Detailed src, uint srcAmount, ERC20Detailed dest, address payable destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes calldata hint) external payable returns(uint); } pragma solidity 0.5.17; interface OneInchExchange { function spender() external view returns (address); } pragma solidity 0.5.17; import "./LongCERC20Order.sol"; import "./LongCEtherOrder.sol"; import "./ShortCERC20Order.sol"; import "./ShortCEtherOrder.sol"; import "../lib/CloneFactory.sol"; contract CompoundOrderFactory is CloneFactory { address public SHORT_CERC20_LOGIC_CONTRACT; address public SHORT_CEther_LOGIC_CONTRACT; address public LONG_CERC20_LOGIC_CONTRACT; address public LONG_CEther_LOGIC_CONTRACT; address public USDC_ADDR; address payable public KYBER_ADDR; address public COMPTROLLER_ADDR; address public ORACLE_ADDR; address public CUSDC_ADDR; address public CETH_ADDR; constructor( address _shortCERC20LogicContract, address _shortCEtherLogicContract, address _longCERC20LogicContract, address _longCEtherLogicContract, address _usdcAddr, address payable _kyberAddr, address _comptrollerAddr, address _priceOracleAddr, address _cUSDCAddr, address _cETHAddr ) public { SHORT_CERC20_LOGIC_CONTRACT = _shortCERC20LogicContract; SHORT_CEther_LOGIC_CONTRACT = _shortCEtherLogicContract; LONG_CERC20_LOGIC_CONTRACT = _longCERC20LogicContract; LONG_CEther_LOGIC_CONTRACT = _longCEtherLogicContract; USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; COMPTROLLER_ADDR = _comptrollerAddr; ORACLE_ADDR = _priceOracleAddr; CUSDC_ADDR = _cUSDCAddr; CETH_ADDR = _cETHAddr; } function createOrder( address _compoundTokenAddr, uint256 _cycleNumber, uint256 _stake, uint256 _collateralAmountInUSDC, uint256 _loanAmountInUSDC, bool _orderType ) external returns (CompoundOrder) { require(_compoundTokenAddr != address(0)); CompoundOrder order; address payable clone; if (_compoundTokenAddr != CETH_ADDR) { if (_orderType) { // Short CERC20 Order clone = toPayableAddr(createClone(SHORT_CERC20_LOGIC_CONTRACT)); } else { // Long CERC20 Order clone = toPayableAddr(createClone(LONG_CERC20_LOGIC_CONTRACT)); } } else { if (_orderType) { // Short CEther Order clone = toPayableAddr(createClone(SHORT_CEther_LOGIC_CONTRACT)); } else { // Long CEther Order clone = toPayableAddr(createClone(LONG_CEther_LOGIC_CONTRACT)); } } order = CompoundOrder(clone); order.init(_compoundTokenAddr, _cycleNumber, _stake, _collateralAmountInUSDC, _loanAmountInUSDC, _orderType, USDC_ADDR, KYBER_ADDR, COMPTROLLER_ADDR, ORACLE_ADDR, CUSDC_ADDR, CETH_ADDR); order.transferOwnership(msg.sender); return order; } function getMarketCollateralFactor(address _compoundTokenAddr) external view returns (uint256) { Comptroller troll = Comptroller(COMPTROLLER_ADDR); (, uint256 factor) = troll.markets(_compoundTokenAddr); return factor; } function tokenIsListed(address _compoundTokenAddr) external view returns (bool) { Comptroller troll = Comptroller(COMPTROLLER_ADDR); (bool isListed,) = troll.markets(_compoundTokenAddr); return isListed; } function toPayableAddr(address _addr) internal pure returns (address payable) { return address(uint160(_addr)); } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract LongCERC20Order is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Convert received USDC to longing token (,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC); // Enter Compound markets CERC20 market = CERC20(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in USDC ERC20Detailed token = __underlyingToken(compoundTokenAddr); token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound token.safeApprove(compoundTokenAddr, actualTokenAmount); // Approve token transfer to Compound require(market.mint(actualTokenAmount) == 0); // Transfer tokens into Compound as supply token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert borrowed USDC to longing token __sellUSDCForToken(loanAmountInUSDC); // Repay leftover USDC to avoid complications if (usdc.balanceOf(address(this)) > 0) { uint256 repayAmount = usdc.balanceOf(address(this)); usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), repayAmount); require(CUSDC.repayBorrow(repayAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted CERC20 market = CERC20(compoundTokenAddr); ERC20Detailed token = __underlyingToken(compoundTokenAddr); for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { liquidity = __usdcToToken(compoundTokenAddr, liquidity); uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Sell all longing token to USDC __sellTokenForUSDC(token.balanceOf(address(this))); // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); uint256 leftoverTokens = token.balanceOf(address(this)); if (leftoverTokens > 0) { token.safeTransfer(owner(), leftoverTokens); // Send back potential leftover tokens } } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert longing token to USDC uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC); (uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken); // Check if amount is greater than borrow balance uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this)); if (actualUSDCAmount > currentDebt) { actualUSDCAmount = currentDebt; } // Repay loan to Compound usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), actualUSDCAmount); require(CUSDC.repayBorrow(actualUSDCAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { CERC20 market = CERC20(compoundTokenAddr); uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION)); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { uint256 borrow = CUSDC.borrowBalanceCurrent(address(this)); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { ERC20Detailed token = __underlyingToken(compoundTokenAddr); uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this))); return cash; } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract LongCEtherOrder is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Convert received USDC to longing token (,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC); // Enter Compound markets CEther market = CEther(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in USDC market.mint.value(actualTokenAmount)(); // Transfer tokens into Compound as supply require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert borrowed USDC to longing token __sellUSDCForToken(loanAmountInUSDC); // Repay leftover USDC to avoid complications if (usdc.balanceOf(address(this)) > 0) { uint256 repayAmount = usdc.balanceOf(address(this)); usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), repayAmount); require(CUSDC.repayBorrow(repayAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted CEther market = CEther(compoundTokenAddr); for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { liquidity = __usdcToToken(compoundTokenAddr, liquidity); uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Sell all longing token to USDC __sellTokenForUSDC(address(this).balance); // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); toPayableAddr(owner()).transfer(address(this).balance); // Send back potential leftover tokens } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert longing token to USDC uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC); (uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken); // Check if amount is greater than borrow balance uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this)); if (actualUSDCAmount > currentDebt) { actualUSDCAmount = currentDebt; } // Repay loan to Compound usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), actualUSDCAmount); require(CUSDC.repayBorrow(actualUSDCAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { CEther market = CEther(compoundTokenAddr); uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION)); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { uint256 borrow = CUSDC.borrowBalanceCurrent(address(this)); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { ERC20Detailed token = __underlyingToken(compoundTokenAddr); uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this))); return cash; } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract ShortCERC20Order is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Enter Compound markets CERC20 market = CERC20(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in tokenAddr uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC); usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply usdc.safeApprove(address(CUSDC), 0); require(market.borrow(loanAmountInToken) == 0);// Take out loan (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert loaned tokens to USDC (uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken); loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received // Repay leftover tokens to avoid complications ERC20Detailed token = __underlyingToken(compoundTokenAddr); if (token.balanceOf(address(this)) > 0) { uint256 repayAmount = token.balanceOf(address(this)); token.safeApprove(compoundTokenAddr, 0); token.safeApprove(compoundTokenAddr, repayAmount); require(market.repayBorrow(repayAmount) == 0); token.safeApprove(compoundTokenAddr, 0); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert USDC to shorting token (,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC); // Check if amount is greater than borrow balance CERC20 market = CERC20(compoundTokenAddr); uint256 currentDebt = market.borrowBalanceCurrent(address(this)); if (actualTokenAmount > currentDebt) { actualTokenAmount = currentDebt; } // Repay loan to Compound ERC20Detailed token = __underlyingToken(compoundTokenAddr); token.safeApprove(compoundTokenAddr, 0); token.safeApprove(compoundTokenAddr, actualTokenAmount); require(market.repayBorrow(actualTokenAmount) == 0); token.safeApprove(compoundTokenAddr, 0); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(CUSDC)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { CERC20 market = CERC20(compoundTokenAddr); uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this))); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { uint256 cash = getBalance(usdc, address(this)); return cash; } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract ShortCEtherOrder is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Enter Compound markets CEther market = CEther(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in tokenAddr uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC); usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply usdc.safeApprove(address(CUSDC), 0); require(market.borrow(loanAmountInToken) == 0);// Take out loan (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert loaned tokens to USDC (uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken); loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received // Repay leftover tokens to avoid complications if (address(this).balance > 0) { uint256 repayAmount = address(this).balance; market.repayBorrow.value(repayAmount)(); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted for (uint256 i = 0; i < MAX_REPAY_STEPS; i = i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert USDC to shorting token (,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC); // Check if amount is greater than borrow balance CEther market = CEther(compoundTokenAddr); uint256 currentDebt = market.borrowBalanceCurrent(address(this)); if (actualTokenAmount > currentDebt) { actualTokenAmount = currentDebt; } // Repay loan to Compound market.repayBorrow.value(actualTokenAmount)(); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(CUSDC)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { CEther market = CEther(compoundTokenAddr); uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this))); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { uint256 cash = getBalance(usdc, address(this)); return cash; } } pragma solidity 0.5.17; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly contract CloneFactory { function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and( eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))) ) } } } pragma solidity 0.5.17; interface IMiniMeToken { function balanceOf(address _owner) external view returns (uint256 balance); function totalSupply() external view returns(uint); function generateTokens(address _owner, uint _amount) external returns (bool); function destroyTokens(address _owner, uint _amount) external returns (bool); function totalSupplyAt(uint _blockNumber) external view returns(uint); function balanceOfAt(address _holder, uint _blockNumber) external view returns (uint); function transferOwnership(address newOwner) external; } pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; function __initReentrancyGuard() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } pragma solidity 0.5.17; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.17; // interface for contract_v6/UniswapOracle.sol interface IUniswapOracle { function update() external returns (bool success); function consult(address token, uint256 amountIn) external view returns (uint256 amountOut); } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; contract PeakToken is ERC20, ERC20Detailed, ERC20Capped, ERC20Burnable { constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap ) ERC20Detailed(name, symbol, decimals) ERC20Capped(cap) public {} } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } pragma solidity ^0.5.0; import "./ERC20Mintable.sol"; /** * @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20Mintable-mint}. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } pragma solidity ^0.5.0; import "./ERC20.sol"; import "../../access/roles/MinterRole.sol"; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "../Roles.sol"; contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/roles/SignerRole.sol"; import "../staking/PeakStaking.sol"; import "../PeakToken.sol"; import "../IUniswapOracle.sol"; contract PeakReward is SignerRole { using SafeMath for uint256; using SafeERC20 for IERC20; event Register(address user, address referrer); event RankChange(address user, uint256 oldRank, uint256 newRank); event PayCommission( address referrer, address recipient, address token, uint256 amount, uint8 level ); event ChangedCareerValue(address user, uint256 changeAmount, bool positive); event ReceiveRankReward(address user, uint256 peakReward); modifier regUser(address user) { if (!isUser[user]) { isUser[user] = true; emit Register(user, address(0)); } _; } uint256 public constant PEAK_MINT_CAP = 5 * 10**15; // 50 million PEAK uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20% uint256 internal constant PEAK_PRECISION = 10**8; uint256 internal constant USDC_PRECISION = 10**6; uint8 internal constant COMMISSION_LEVELS = 8; mapping(address => address) public referrerOf; mapping(address => bool) public isUser; mapping(address => uint256) public careerValue; // AKA DSV mapping(address => uint256) public rankOf; mapping(uint256 => mapping(uint256 => uint256)) public rankReward; // (beforeRank, afterRank) => rewardInPeak mapping(address => mapping(uint256 => uint256)) public downlineRanks; // (referrer, rank) => numReferredUsersWithRank uint256[] public commissionPercentages; uint256[] public commissionStakeRequirements; uint256 public mintedPeakTokens; address public marketPeakWallet; PeakStaking public peakStaking; PeakToken public peakToken; address public stablecoin; IUniswapOracle public oracle; constructor( address _marketPeakWallet, address _peakStaking, address _peakToken, address _stablecoin, address _oracle ) public { // initialize commission percentages for each level commissionPercentages.push(10 * (10**16)); // 10% commissionPercentages.push(4 * (10**16)); // 4% commissionPercentages.push(2 * (10**16)); // 2% commissionPercentages.push(1 * (10**16)); // 1% commissionPercentages.push(1 * (10**16)); // 1% commissionPercentages.push(1 * (10**16)); // 1% commissionPercentages.push(5 * (10**15)); // 0.5% commissionPercentages.push(5 * (10**15)); // 0.5% // initialize commission stake requirements for each level commissionStakeRequirements.push(0); commissionStakeRequirements.push(PEAK_PRECISION.mul(2000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(4000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(6000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(7000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(8000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(9000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(10000)); // initialize rank rewards for (uint256 i = 0; i < 8; i = i.add(1)) { uint256 rewardInUSDC = 0; for (uint256 j = i.add(1); j <= 8; j = j.add(1)) { if (j == 1) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(100)); } else if (j == 2) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(300)); } else if (j == 3) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(600)); } else if (j == 4) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(1200)); } else if (j == 5) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(2400)); } else if (j == 6) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(7500)); } else if (j == 7) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(15000)); } else { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(50000)); } rankReward[i][j] = rewardInUSDC; } } marketPeakWallet = _marketPeakWallet; peakStaking = PeakStaking(_peakStaking); peakToken = PeakToken(_peakToken); stablecoin = _stablecoin; oracle = IUniswapOracle(_oracle); } /** @notice Registers a group of referrals relationship. @param users The array of users @param referrers The group of referrers of `users` */ function multiRefer(address[] calldata users, address[] calldata referrers) external onlySigner { require(users.length == referrers.length, "PeakReward: arrays length are not equal"); for (uint256 i = 0; i < users.length; i++) { refer(users[i], referrers[i]); } } /** @notice Registers a referral relationship @param user The user who is being referred @param referrer The referrer of `user` */ function refer(address user, address referrer) public onlySigner { require(!isUser[user], "PeakReward: referred is already a user"); require(user != referrer, "PeakReward: can't refer self"); require( user != address(0) && referrer != address(0), "PeakReward: 0 address" ); isUser[user] = true; isUser[referrer] = true; referrerOf[user] = referrer; downlineRanks[referrer][0] = downlineRanks[referrer][0].add(1); emit Register(user, referrer); } function canRefer(address user, address referrer) public view returns (bool) { return !isUser[user] && user != referrer && user != address(0) && referrer != address(0); } /** @notice Distributes commissions to a referrer and their referrers @param referrer The referrer who will receive commission @param commissionToken The ERC20 token that the commission is paid in @param rawCommission The raw commission that will be distributed amongst referrers @param returnLeftovers If true, leftover commission is returned to the sender. If false, leftovers will be paid to MarketPeak. */ function payCommission( address referrer, address commissionToken, uint256 rawCommission, bool returnLeftovers ) public regUser(referrer) onlySigner returns (uint256 leftoverAmount) { // transfer the raw commission from `msg.sender` IERC20 token = IERC20(commissionToken); token.safeTransferFrom(msg.sender, address(this), rawCommission); // payout commissions to referrers of different levels address ptr = referrer; uint256 commissionLeft = rawCommission; uint8 i = 0; while (ptr != address(0) && i < COMMISSION_LEVELS) { if (_peakStakeOf(ptr) >= commissionStakeRequirements[i]) { // referrer has enough stake, give commission uint256 com = rawCommission.mul(commissionPercentages[i]).div( COMMISSION_RATE ); if (com > commissionLeft) { com = commissionLeft; } token.safeTransfer(ptr, com); commissionLeft = commissionLeft.sub(com); if (commissionToken == address(peakToken)) { incrementCareerValueInPeak(ptr, com); } else if (commissionToken == stablecoin) { incrementCareerValueInUsdc(ptr, com); } emit PayCommission(referrer, ptr, commissionToken, com, i); } ptr = referrerOf[ptr]; i += 1; } // handle leftovers if (returnLeftovers) { // return leftovers to `msg.sender` token.safeTransfer(msg.sender, commissionLeft); return commissionLeft; } else { // give leftovers to MarketPeak wallet token.safeTransfer(marketPeakWallet, commissionLeft); return 0; } } /** @notice Increments a user's career value @param user The user @param incCV The CV increase amount, in Usdc */ function incrementCareerValueInUsdc(address user, uint256 incCV) public regUser(user) onlySigner { careerValue[user] = careerValue[user].add(incCV); emit ChangedCareerValue(user, incCV, true); } /** @notice Increments a user's career value @param user The user @param incCVInPeak The CV increase amount, in PEAK tokens */ function incrementCareerValueInPeak(address user, uint256 incCVInPeak) public regUser(user) onlySigner { uint256 peakPriceInUsdc = _getPeakPriceInUsdc(); uint256 incCVInUsdc = incCVInPeak.mul(peakPriceInUsdc).div( PEAK_PRECISION ); careerValue[user] = careerValue[user].add(incCVInUsdc); emit ChangedCareerValue(user, incCVInUsdc, true); } /** @notice Returns a user's rank in the PeakDeFi system based only on career value @param user The user whose rank will be queried */ function cvRankOf(address user) public view returns (uint256) { uint256 cv = careerValue[user]; if (cv < USDC_PRECISION.mul(100)) { return 0; } else if (cv < USDC_PRECISION.mul(250)) { return 1; } else if (cv < USDC_PRECISION.mul(750)) { return 2; } else if (cv < USDC_PRECISION.mul(1500)) { return 3; } else if (cv < USDC_PRECISION.mul(3000)) { return 4; } else if (cv < USDC_PRECISION.mul(10000)) { return 5; } else if (cv < USDC_PRECISION.mul(50000)) { return 6; } else if (cv < USDC_PRECISION.mul(150000)) { return 7; } else { return 8; } } function rankUp(address user) external { // verify rank up conditions uint256 currentRank = rankOf[user]; uint256 cvRank = cvRankOf(user); require(cvRank > currentRank, "PeakReward: career value is not enough!"); require(downlineRanks[user][currentRank] >= 2 || currentRank == 0, "PeakReward: downlines count and requirement not passed!"); // Target rank always should be +1 rank from current rank uint256 targetRank = currentRank + 1; // increase user rank rankOf[user] = targetRank; emit RankChange(user, currentRank, targetRank); address referrer = referrerOf[user]; if (referrer != address(0)) { downlineRanks[referrer][targetRank] = downlineRanks[referrer][targetRank] .add(1); downlineRanks[referrer][currentRank] = downlineRanks[referrer][currentRank] .sub(1); } // give user rank reward uint256 rewardInPeak = rankReward[currentRank][targetRank] .mul(PEAK_PRECISION) .div(_getPeakPriceInUsdc()); if (mintedPeakTokens.add(rewardInPeak) <= PEAK_MINT_CAP) { // mint if under cap, do nothing if over cap mintedPeakTokens = mintedPeakTokens.add(rewardInPeak); peakToken.mint(user, rewardInPeak); emit ReceiveRankReward(user, rewardInPeak); } } function canRankUp(address user) external view returns (bool) { uint256 currentRank = rankOf[user]; uint256 cvRank = cvRankOf(user); return (cvRank > currentRank) && (downlineRanks[user][currentRank] >= 2 || currentRank == 0); } /** @notice Returns a user's current staked PEAK amount, scaled by `PEAK_PRECISION`. @param user The user whose stake will be queried */ function _peakStakeOf(address user) internal view returns (uint256) { return peakStaking.userStakeAmount(user); } /** @notice Returns the price of PEAK token in Usdc, scaled by `USDC_PRECISION`. */ function _getPeakPriceInUsdc() internal returns (uint256) { oracle.update(); uint256 priceInUSDC = oracle.consult(address(peakToken), PEAK_PRECISION); if (priceInUSDC == 0) { return USDC_PRECISION.mul(3).div(10); } return priceInUSDC; } } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "../Roles.sol"; contract SignerRole is Context { using Roles for Roles.Role; event SignerAdded(address indexed account); event SignerRemoved(address indexed account); Roles.Role private _signers; constructor () internal { _addSigner(_msgSender()); } modifier onlySigner() { require(isSigner(_msgSender()), "SignerRole: caller does not have the Signer role"); _; } function isSigner(address account) public view returns (bool) { return _signers.has(account); } function addSigner(address account) public onlySigner { _addSigner(account); } function renounceSigner() public { _removeSigner(_msgSender()); } function _addSigner(address account) internal { _signers.add(account); emit SignerAdded(account); } function _removeSigner(address account) internal { _signers.remove(account); emit SignerRemoved(account); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../reward/PeakReward.sol"; import "../PeakToken.sol"; contract PeakStaking { using SafeMath for uint256; using SafeERC20 for PeakToken; event CreateStake( uint256 idx, address user, address referrer, uint256 stakeAmount, uint256 stakeTimeInDays, uint256 interestAmount ); event ReceiveStakeReward(uint256 idx, address user, uint256 rewardAmount); event WithdrawReward(uint256 idx, address user, uint256 rewardAmount); event WithdrawStake(uint256 idx, address user); uint256 internal constant PRECISION = 10**18; uint256 internal constant PEAK_PRECISION = 10**8; uint256 internal constant INTEREST_SLOPE = 2 * (10**8); // Interest rate factor drops to 0 at 5B mintedPeakTokens uint256 internal constant BIGGER_BONUS_DIVISOR = 10**15; // biggerBonus = stakeAmount / (10 million peak) uint256 internal constant MAX_BIGGER_BONUS = 10**17; // biggerBonus <= 10% uint256 internal constant DAILY_BASE_REWARD = 15 * (10**14); // dailyBaseReward = 0.0015 uint256 internal constant DAILY_GROWING_REWARD = 10**12; // dailyGrowingReward = 1e-6 uint256 internal constant MAX_STAKE_PERIOD = 1000; // Max staking time is 1000 days uint256 internal constant MIN_STAKE_PERIOD = 10; // Min staking time is 10 days uint256 internal constant DAY_IN_SECONDS = 86400; uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20% uint256 internal constant REFERRAL_STAKER_BONUS = 3 * (10**16); // 3% uint256 internal constant YEAR_IN_DAYS = 365; uint256 public constant PEAK_MINT_CAP = 7 * 10**16; // 700 million PEAK struct Stake { address staker; uint256 stakeAmount; uint256 interestAmount; uint256 withdrawnInterestAmount; uint256 stakeTimestamp; uint256 stakeTimeInDays; bool active; } Stake[] public stakeList; mapping(address => uint256) public userStakeAmount; uint256 public mintedPeakTokens; bool public initialized; PeakToken public peakToken; PeakReward public peakReward; constructor(address _peakToken) public { peakToken = PeakToken(_peakToken); } function init(address _peakReward) public { require(!initialized, "PeakStaking: Already initialized"); initialized = true; peakReward = PeakReward(_peakReward); } function stake( uint256 stakeAmount, uint256 stakeTimeInDays, address referrer ) public returns (uint256 stakeIdx) { require( stakeTimeInDays >= MIN_STAKE_PERIOD, "PeakStaking: stakeTimeInDays < MIN_STAKE_PERIOD" ); require( stakeTimeInDays <= MAX_STAKE_PERIOD, "PeakStaking: stakeTimeInDays > MAX_STAKE_PERIOD" ); // record stake uint256 interestAmount = getInterestAmount( stakeAmount, stakeTimeInDays ); stakeIdx = stakeList.length; stakeList.push( Stake({ staker: msg.sender, stakeAmount: stakeAmount, interestAmount: interestAmount, withdrawnInterestAmount: 0, stakeTimestamp: now, stakeTimeInDays: stakeTimeInDays, active: true }) ); mintedPeakTokens = mintedPeakTokens.add(interestAmount); userStakeAmount[msg.sender] = userStakeAmount[msg.sender].add( stakeAmount ); // transfer PEAK from msg.sender peakToken.safeTransferFrom(msg.sender, address(this), stakeAmount); // mint PEAK interest peakToken.mint(address(this), interestAmount); // handle referral if (peakReward.canRefer(msg.sender, referrer)) { peakReward.refer(msg.sender, referrer); } address actualReferrer = peakReward.referrerOf(msg.sender); if (actualReferrer != address(0)) { // pay referral bonus to referrer uint256 rawCommission = interestAmount.mul(COMMISSION_RATE).div( PRECISION ); peakToken.mint(address(this), rawCommission); peakToken.safeApprove(address(peakReward), rawCommission); uint256 leftoverAmount = peakReward.payCommission( actualReferrer, address(peakToken), rawCommission, true ); peakToken.burn(leftoverAmount); // pay referral bonus to staker uint256 referralStakerBonus = interestAmount .mul(REFERRAL_STAKER_BONUS) .div(PRECISION); peakToken.mint(msg.sender, referralStakerBonus); mintedPeakTokens = mintedPeakTokens.add( rawCommission.sub(leftoverAmount).add(referralStakerBonus) ); emit ReceiveStakeReward(stakeIdx, msg.sender, referralStakerBonus); } require(mintedPeakTokens <= PEAK_MINT_CAP, "PeakStaking: reached cap"); emit CreateStake( stakeIdx, msg.sender, actualReferrer, stakeAmount, stakeTimeInDays, interestAmount ); } function withdraw(uint256 stakeIdx) public { Stake storage stakeObj = stakeList[stakeIdx]; require( stakeObj.staker == msg.sender, "PeakStaking: Sender not staker" ); require(stakeObj.active, "PeakStaking: Not active"); // calculate amount that can be withdrawn uint256 stakeTimeInSeconds = stakeObj.stakeTimeInDays.mul( DAY_IN_SECONDS ); uint256 withdrawAmount; if (now >= stakeObj.stakeTimestamp.add(stakeTimeInSeconds)) { // matured, withdraw all withdrawAmount = stakeObj .stakeAmount .add(stakeObj.interestAmount) .sub(stakeObj.withdrawnInterestAmount); stakeObj.active = false; stakeObj.withdrawnInterestAmount = stakeObj.interestAmount; userStakeAmount[msg.sender] = userStakeAmount[msg.sender].sub( stakeObj.stakeAmount ); emit WithdrawReward( stakeIdx, msg.sender, stakeObj.interestAmount.sub(stakeObj.withdrawnInterestAmount) ); emit WithdrawStake(stakeIdx, msg.sender); } else { // not mature, partial withdraw withdrawAmount = stakeObj .interestAmount .mul(uint256(now).sub(stakeObj.stakeTimestamp)) .div(stakeTimeInSeconds) .sub(stakeObj.withdrawnInterestAmount); // record withdrawal stakeObj.withdrawnInterestAmount = stakeObj .withdrawnInterestAmount .add(withdrawAmount); emit WithdrawReward(stakeIdx, msg.sender, withdrawAmount); } // withdraw interest to sender peakToken.safeTransfer(msg.sender, withdrawAmount); } function getInterestAmount(uint256 stakeAmount, uint256 stakeTimeInDays) public view returns (uint256) { uint256 earlyFactor = _earlyFactor(mintedPeakTokens); uint256 biggerBonus = stakeAmount.mul(PRECISION).div( BIGGER_BONUS_DIVISOR ); if (biggerBonus > MAX_BIGGER_BONUS) { biggerBonus = MAX_BIGGER_BONUS; } // convert yearly bigger bonus to stake time biggerBonus = biggerBonus.mul(stakeTimeInDays).div(YEAR_IN_DAYS); uint256 longerBonus = _longerBonus(stakeTimeInDays); uint256 interestRate = biggerBonus.add(longerBonus).mul(earlyFactor).div( PRECISION ); uint256 interestAmount = stakeAmount.mul(interestRate).div(PRECISION); return interestAmount; } function _longerBonus(uint256 stakeTimeInDays) internal pure returns (uint256) { return DAILY_BASE_REWARD.mul(stakeTimeInDays).add( DAILY_GROWING_REWARD .mul(stakeTimeInDays) .mul(stakeTimeInDays.add(1)) .div(2) ); } function _earlyFactor(uint256 _mintedPeakTokens) internal pure returns (uint256) { uint256 tmp = INTEREST_SLOPE.mul(_mintedPeakTokens).div(PEAK_PRECISION); if (tmp > PRECISION) { return 0; } return PRECISION.sub(tmp); } } pragma solidity 0.5.17; import "./lib/CloneFactory.sol"; import "./tokens/minime/MiniMeToken.sol"; import "./PeakDeFiFund.sol"; import "./PeakDeFiProxy.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract PeakDeFiFactory is CloneFactory { using Address for address; event CreateFund(address fund); event InitFund(address fund, address proxy); address public usdcAddr; address payable public kyberAddr; address payable public oneInchAddr; address payable public peakdefiFund; address public peakdefiLogic; address public peakdefiLogic2; address public peakdefiLogic3; address public peakRewardAddr; address public peakStakingAddr; MiniMeTokenFactory public minimeFactory; mapping(address => address) public fundCreator; constructor( address _usdcAddr, address payable _kyberAddr, address payable _oneInchAddr, address payable _peakdefiFund, address _peakdefiLogic, address _peakdefiLogic2, address _peakdefiLogic3, address _peakRewardAddr, address _peakStakingAddr, address _minimeFactoryAddr ) public { usdcAddr = _usdcAddr; kyberAddr = _kyberAddr; oneInchAddr = _oneInchAddr; peakdefiFund = _peakdefiFund; peakdefiLogic = _peakdefiLogic; peakdefiLogic2 = _peakdefiLogic2; peakdefiLogic3 = _peakdefiLogic3; peakRewardAddr = _peakRewardAddr; peakStakingAddr = _peakStakingAddr; minimeFactory = MiniMeTokenFactory(_minimeFactoryAddr); } function createFund() external returns (PeakDeFiFund) { // create fund PeakDeFiFund fund = PeakDeFiFund(createClone(peakdefiFund).toPayable()); fund.initOwner(); // give PeakReward signer rights to fund PeakReward peakReward = PeakReward(peakRewardAddr); peakReward.addSigner(address(fund)); fundCreator[address(fund)] = msg.sender; emit CreateFund(address(fund)); return fund; } function initFund1( PeakDeFiFund fund, string calldata reptokenName, string calldata reptokenSymbol, string calldata sharesName, string calldata sharesSymbol ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); // create tokens MiniMeToken reptoken = minimeFactory.createCloneToken( address(0), 0, reptokenName, 18, reptokenSymbol, false ); MiniMeToken shares = minimeFactory.createCloneToken( address(0), 0, sharesName, 18, sharesSymbol, true ); MiniMeToken peakReferralToken = minimeFactory.createCloneToken( address(0), 0, "Peak Referral Token", 18, "PRT", false ); // transfer token ownerships to fund reptoken.transferOwnership(address(fund)); shares.transferOwnership(address(fund)); peakReferralToken.transferOwnership(address(fund)); fund.initInternalTokens( address(reptoken), address(shares), address(peakReferralToken) ); } function initFund2( PeakDeFiFund fund, address payable _devFundingAccount, uint256 _devFundingRate, uint256[2] calldata _phaseLengths, address _compoundFactoryAddr ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); fund.initParams( _devFundingAccount, _phaseLengths, _devFundingRate, address(0), usdcAddr, kyberAddr, _compoundFactoryAddr, peakdefiLogic, peakdefiLogic2, peakdefiLogic3, 1, oneInchAddr, peakRewardAddr, peakStakingAddr ); } function initFund3( PeakDeFiFund fund, uint256 _newManagerRepToken, uint256 _maxNewManagersPerCycle, uint256 _reptokenPrice, uint256 _peakManagerStakeRequired, bool _isPermissioned ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); fund.initRegistration( _newManagerRepToken, _maxNewManagersPerCycle, _reptokenPrice, _peakManagerStakeRequired, _isPermissioned ); } function initFund4( PeakDeFiFund fund, address[] calldata _kyberTokens, address[] calldata _compoundTokens ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); fund.initTokenListings(_kyberTokens, _compoundTokens); // deploy and set PeakDeFiProxy PeakDeFiProxy proxy = new PeakDeFiProxy(address(fund)); fund.setProxy(address(proxy).toPayable()); // transfer fund ownership to msg.sender fund.transferOwnership(msg.sender); emit InitFund(address(fund), address(proxy)); } } pragma solidity 0.5.17; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./TokenController.sol"; contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public; } /// @dev The actual token contract, the default owner is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token owner contract, which Giveth will call a "Campaign" contract MiniMeToken is Ownable { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.2"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred constructor( address _tokenFactory, address payable _parentToken, uint _parentSnapShotBlock, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // The owner of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // owner of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != owner()) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != address(0)) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // Alerts the token owner of the transfer if (isContract(owner())) { require(TokenController(owner()).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token owner of the approve function call if (isContract(owner())) { require(TokenController(owner()).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes memory _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, address(this), _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public view returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != address(0)) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public view returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != address(0)) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string memory _cloneTokenName, uint8 _cloneDecimalUnits, string memory _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { uint snapshotBlock = _snapshotBlock; if (snapshotBlock == 0) snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( address(this), snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.transferOwnership(msg.sender); // An event to make the token easy to find on the blockchain emit NewCloneToken(address(cloneToken), snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) public onlyOwner returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); emit Transfer(address(0), _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyOwner public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); emit Transfer(_owner, address(0), _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyOwner { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) view internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) view internal returns(bool) { uint size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's owner has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token owner contract function () external payable { require(isContract(owner())); require(TokenController(owner()).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address payable _token) public onlyOwner { if (_token == address(0)) { address(uint160(owner())).transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(address(this)); require(token.transfer(owner(), balance)); emit ClaimedTokens(_token, owner(), balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { event CreatedToken(string symbol, address addr); /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the owner of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address payable _parentToken, uint _snapshotBlock, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( address(this), _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.transferOwnership(msg.sender); emit CreatedToken(_tokenSymbol, address(newToken)); return newToken; } } pragma solidity 0.5.17; /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } pragma solidity 0.5.17; import "./PeakDeFiStorage.sol"; import "./derivatives/CompoundOrderFactory.sol"; /** * @title The main smart contract of the PeakDeFi hedge fund. * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiFund is PeakDeFiStorage, Utils(address(0), address(0), address(0)), TokenController { /** * @notice Passes if the fund is ready for migrating to the next version */ modifier readyForUpgradeMigration { require(hasFinalizedNextVersion == true); require( now > startTimeOfCyclePhase.add( phaseLengths[uint256(CyclePhase.Intermission)] ) ); _; } /** * Meta functions */ function initParams( address payable _devFundingAccount, uint256[2] calldata _phaseLengths, uint256 _devFundingRate, address payable _previousVersion, address _usdcAddr, address payable _kyberAddr, address _compoundFactoryAddr, address _peakdefiLogic, address _peakdefiLogic2, address _peakdefiLogic3, uint256 _startCycleNumber, address payable _oneInchAddr, address _peakRewardAddr, address _peakStakingAddr ) external { require(proxyAddr == address(0)); devFundingAccount = _devFundingAccount; phaseLengths = _phaseLengths; devFundingRate = _devFundingRate; cyclePhase = CyclePhase.Intermission; compoundFactoryAddr = _compoundFactoryAddr; peakdefiLogic = _peakdefiLogic; peakdefiLogic2 = _peakdefiLogic2; peakdefiLogic3 = _peakdefiLogic3; previousVersion = _previousVersion; cycleNumber = _startCycleNumber; peakReward = PeakReward(_peakRewardAddr); peakStaking = PeakStaking(_peakStakingAddr); USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; ONEINCH_ADDR = _oneInchAddr; usdc = ERC20Detailed(_usdcAddr); kyber = KyberNetwork(_kyberAddr); __initReentrancyGuard(); } function initOwner() external { require(proxyAddr == address(0)); _transferOwnership(msg.sender); } function initInternalTokens( address payable _repAddr, address payable _sTokenAddr, address payable _peakReferralTokenAddr ) external onlyOwner { require(controlTokenAddr == address(0)); require(_repAddr != address(0)); controlTokenAddr = _repAddr; shareTokenAddr = _sTokenAddr; cToken = IMiniMeToken(_repAddr); sToken = IMiniMeToken(_sTokenAddr); peakReferralToken = IMiniMeToken(_peakReferralTokenAddr); } function initRegistration( uint256 _newManagerRepToken, uint256 _maxNewManagersPerCycle, uint256 _reptokenPrice, uint256 _peakManagerStakeRequired, bool _isPermissioned ) external onlyOwner { require(_newManagerRepToken > 0 && newManagerRepToken == 0); newManagerRepToken = _newManagerRepToken; maxNewManagersPerCycle = _maxNewManagersPerCycle; reptokenPrice = _reptokenPrice; peakManagerStakeRequired = _peakManagerStakeRequired; isPermissioned = _isPermissioned; } function initTokenListings( address[] calldata _kyberTokens, address[] calldata _compoundTokens ) external onlyOwner { // May only initialize once require(!hasInitializedTokenListings); hasInitializedTokenListings = true; uint256 i; for (i = 0; i < _kyberTokens.length; i++) { isKyberToken[_kyberTokens[i]] = true; } CompoundOrderFactory factory = CompoundOrderFactory(compoundFactoryAddr); for (i = 0; i < _compoundTokens.length; i++) { require(factory.tokenIsListed(_compoundTokens[i])); isCompoundToken[_compoundTokens[i]] = true; } } /** * @notice Used during deployment to set the PeakDeFiProxy contract address. * @param _proxyAddr the proxy's address */ function setProxy(address payable _proxyAddr) external onlyOwner { require(_proxyAddr != address(0)); require(proxyAddr == address(0)); proxyAddr = _proxyAddr; proxy = PeakDeFiProxyInterface(_proxyAddr); } /** * Upgrading functions */ /** * @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to. * The developer may change the candidate during the Intermission phase. * @param _candidate the address of the candidate smart contract * @return True if successfully changed candidate, false otherwise. */ function developerInitiateUpgrade(address payable _candidate) public returns (bool _success) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.developerInitiateUpgrade.selector, _candidate ) ); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Transfers ownership of RepToken & Share token contracts to the next version. Also updates PeakDeFiFund's * address in PeakDeFiProxy. */ function migrateOwnedContractsToNextVersion() public nonReentrant readyForUpgradeMigration { cToken.transferOwnership(nextVersion); sToken.transferOwnership(nextVersion); peakReferralToken.transferOwnership(nextVersion); proxy.updatePeakDeFiFundAddress(); } /** * @notice Transfers assets to the next version. * @param _assetAddress the address of the asset to be transferred. Use ETH_TOKEN_ADDRESS to transfer Ether. */ function transferAssetToNextVersion(address _assetAddress) public nonReentrant readyForUpgradeMigration isValidToken(_assetAddress) { if (_assetAddress == address(ETH_TOKEN_ADDRESS)) { nextVersion.transfer(address(this).balance); } else { ERC20Detailed token = ERC20Detailed(_assetAddress); token.safeTransfer(nextVersion, token.balanceOf(address(this))); } } /** * Getters */ /** * @notice Returns the length of the user's investments array. * @return length of the user's investments array */ function investmentsCount(address _userAddr) public view returns (uint256 _count) { return userInvestments[_userAddr].length; } /** * @notice Returns the length of the user's compound orders array. * @return length of the user's compound orders array */ function compoundOrdersCount(address _userAddr) public view returns (uint256 _count) { return userCompoundOrders[_userAddr].length; } /** * @notice Returns the phaseLengths array. * @return the phaseLengths array */ function getPhaseLengths() public view returns (uint256[2] memory _phaseLengths) { return phaseLengths; } /** * @notice Returns the commission balance of `_manager` * @return the commission balance and the received penalty, denoted in USDC */ function commissionBalanceOf(address _manager) public returns (uint256 _commission, uint256 _penalty) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.commissionBalanceOf.selector, _manager) ); if (!success) { return (0, 0); } return abi.decode(result, (uint256, uint256)); } /** * @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in USDC */ function commissionOfAt(address _manager, uint256 _cycle) public returns (uint256 _commission, uint256 _penalty) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.commissionOfAt.selector, _manager, _cycle ) ); if (!success) { return (0, 0); } return abi.decode(result, (uint256, uint256)); } /** * Parameter setters */ /** * @notice Changes the address to which the developer fees will be sent. Only callable by owner. * @param _newAddr the new developer fee address */ function changeDeveloperFeeAccount(address payable _newAddr) public onlyOwner { require(_newAddr != address(0) && _newAddr != address(this)); devFundingAccount = _newAddr; } /** * @notice Changes the proportion of fund balance sent to the developers each cycle. May only decrease. Only callable by owner. * @param _newProp the new proportion, fixed point decimal */ function changeDeveloperFeeRate(uint256 _newProp) public onlyOwner { require(_newProp < PRECISION); require(_newProp < devFundingRate); devFundingRate = _newProp; } /** * @notice Allows managers to invest in a token. Only callable by owner. * @param _token address of the token to be listed */ function listKyberToken(address _token) public onlyOwner { isKyberToken[_token] = true; } /** * @notice Allows managers to invest in a Compound token. Only callable by owner. * @param _token address of the Compound token to be listed */ function listCompoundToken(address _token) public onlyOwner { CompoundOrderFactory factory = CompoundOrderFactory( compoundFactoryAddr ); require(factory.tokenIsListed(_token)); isCompoundToken[_token] = true; } /** * @notice Moves the fund to the next phase in the investment cycle. */ function nextPhase() public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.nextPhase.selector) ); if (!success) { revert(); } } /** * Manager registration */ /** * @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithUSDC() public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.registerWithUSDC.selector) ); if (!success) { revert(); } } /** * @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithETH() public payable { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.registerWithETH.selector) ); if (!success) { revert(); } } /** * @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. * @param _token the token to be used for payment * @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals */ function registerWithToken(address _token, uint256 _donationInTokens) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.registerWithToken.selector, _token, _donationInTokens ) ); if (!success) { revert(); } } /** * Intermission phase functions */ /** * @notice Deposit Ether into the fund. Ether will be converted into USDC. */ function depositEther(address _referrer) public payable { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.depositEther.selector, _referrer) ); if (!success) { revert(); } } function depositEtherAdvanced( bool _useKyber, bytes calldata _calldata, address _referrer ) external payable { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositEtherAdvanced.selector, _useKyber, _calldata, _referrer ) ); if (!success) { revert(); } } /** * @notice Deposit USDC Stablecoin into the fund. * @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount. */ function depositUSDC(uint256 _usdcAmount, address _referrer) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositUSDC.selector, _usdcAmount, _referrer ) ); if (!success) { revert(); } } /** * @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC. * @param _tokenAddr the address of the token to be deposited * @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount. */ function depositToken( address _tokenAddr, uint256 _tokenAmount, address _referrer ) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositToken.selector, _tokenAddr, _tokenAmount, _referrer ) ); if (!success) { revert(); } } function depositTokenAdvanced( address _tokenAddr, uint256 _tokenAmount, bool _useKyber, bytes calldata _calldata, address _referrer ) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositTokenAdvanced.selector, _tokenAddr, _tokenAmount, _useKyber, _calldata, _referrer ) ); if (!success) { revert(); } } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawEther(uint256 _amountInUSDC) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.withdrawEther.selector, _amountInUSDC) ); if (!success) { revert(); } } function withdrawEtherAdvanced( uint256 _amountInUSDC, bool _useKyber, bytes calldata _calldata ) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.withdrawEtherAdvanced.selector, _amountInUSDC, _useKyber, _calldata ) ); if (!success) { revert(); } } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawUSDC(uint256 _amountInUSDC) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.withdrawUSDC.selector, _amountInUSDC) ); if (!success) { revert(); } } /** * @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network. * @param _tokenAddr the address of the token to be withdrawn into the caller's account * @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.withdrawToken.selector, _tokenAddr, _amountInUSDC ) ); if (!success) { revert(); } } function withdrawTokenAdvanced( address _tokenAddr, uint256 _amountInUSDC, bool _useKyber, bytes calldata _calldata ) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.withdrawTokenAdvanced.selector, _tokenAddr, _amountInUSDC, _useKyber, _calldata ) ); if (!success) { revert(); } } /** * @notice Redeems commission. */ function redeemCommission(bool _inShares) public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.redeemCommission.selector, _inShares) ); if (!success) { revert(); } } /** * @notice Redeems commission for a particular cycle. * @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function redeemCommissionForCycle(bool _inShares, uint256 _cycle) public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.redeemCommissionForCycle.selector, _inShares, _cycle ) ); if (!success) { revert(); } } /** * @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _tokenAddr address of the token to be sold * @param _calldata the 1inch trade call data */ function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.sellLeftoverToken.selector, _tokenAddr, _calldata ) ); if (!success) { revert(); } } /** * @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _orderAddress address of the CompoundOrder to be sold */ function sellLeftoverCompoundOrder(address payable _orderAddress) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.sellLeftoverCompoundOrder.selector, _orderAddress ) ); if (!success) { revert(); } } /** * @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles * @param _deadman the manager whose RepToken balance will be burned */ function burnDeadman(address _deadman) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector(this.burnDeadman.selector, _deadman) ); if (!success) { revert(); } } /** * Manage phase functions */ function createInvestmentWithSignature( address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createInvestmentWithSignature.selector, _tokenAddress, _stake, _maxPrice, _calldata, _useKyber, _manager, _salt, _signature ) ); if (!success) { revert(); } } function sellInvestmentWithSignature( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellInvestmentWithSignature.selector, _investmentId, _tokenAmount, _minPrice, _maxPrice, _calldata, _useKyber, _manager, _salt, _signature ) ); if (!success) { revert(); } } function createCompoundOrderWithSignature( bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createCompoundOrderWithSignature.selector, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice, _manager, _salt, _signature ) ); if (!success) { revert(); } } function sellCompoundOrderWithSignature( uint256 _orderId, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellCompoundOrderWithSignature.selector, _orderId, _minPrice, _maxPrice, _manager, _salt, _signature ) ); if (!success) { revert(); } } function repayCompoundOrderWithSignature( uint256 _orderId, uint256 _repayAmountInUSDC, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.repayCompoundOrderWithSignature.selector, _orderId, _repayAmountInUSDC, _manager, _salt, _signature ) ); if (!success) { revert(); } } /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade */ function createInvestment( address _tokenAddress, uint256 _stake, uint256 _maxPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createInvestment.selector, _tokenAddress, _stake, _maxPrice ) ); if (!success) { revert(); } } /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade * @param _calldata calldata for 1inch trading * @param _useKyber true for Kyber Network, false for 1inch */ function createInvestmentV2( address _sender, address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes memory _calldata, bool _useKyber ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createInvestmentV2.selector, _sender, _tokenAddress, _stake, _maxPrice, _calldata, _useKyber ) ); if (!success) { revert(); } } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAsset( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellInvestmentAsset.selector, _investmentId, _tokenAmount, _minPrice ) ); if (!success) { revert(); } } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAssetV2( address _sender, uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes memory _calldata, bool _useKyber ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellInvestmentAssetV2.selector, _sender, _investmentId, _tokenAmount, _minPrice, _calldata, _useKyber ) ); if (!success) { revert(); } } /** * @notice Creates a new Compound order to either short or leverage long a token. * @param _orderType true for a short order, false for a levarage long order * @param _tokenAddress address of the Compound token to be traded * @param _stake amount of RepTokens to be staked * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function createCompoundOrder( address _sender, bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createCompoundOrder.selector, _sender, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice ) ); if (!success) { revert(); } } /** * @notice Sells a compound order * @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender]) * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function sellCompoundOrder( address _sender, uint256 _orderId, uint256 _minPrice, uint256 _maxPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellCompoundOrder.selector, _sender, _orderId, _minPrice, _maxPrice ) ); if (!success) { revert(); } } /** * @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold. * @param _orderId the ID of the Compound order * @param _repayAmountInUSDC amount of USDC to use for repaying debt */ function repayCompoundOrder( address _sender, uint256 _orderId, uint256 _repayAmountInUSDC ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.repayCompoundOrder.selector, _sender, _orderId, _repayAmountInUSDC ) ); if (!success) { revert(); } } /** * @notice Emergency exit the tokens from order contract during intermission stage * @param _sender the address of trader, who created the order * @param _orderId the ID of the Compound order * @param _tokenAddr the address of token which should be transferred * @param _receiver the address of receiver */ function emergencyExitCompoundTokens( address _sender, uint256 _orderId, address _tokenAddr, address _receiver ) public onlyOwner { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.emergencyExitCompoundTokens.selector, _sender, _orderId, _tokenAddr, _receiver ) ); if (!success) { revert(); } } /** * Internal use functions */ // MiniMe TokenController functions, not used right now /** * @notice Called when `_owner` sends ether to the MiniMe Token contract * @return True if the ether is accepted, false if it throws */ function proxyPayment( address /*_owner*/ ) public payable returns (bool) { return false; } /** * @notice Notifies the controller about a token transfer allowing the * controller to react if desired * @return False if the controller does not authorize the transfer */ function onTransfer( address, /*_from*/ address, /*_to*/ uint256 /*_amount*/ ) public returns (bool) { return true; } /** * @notice Notifies the controller about an approval allowing the * controller to react if desired * @return False if the controller does not authorize the approval */ function onApprove( address, /*_owner*/ address, /*_spender*/ uint256 /*_amount*/ ) public returns (bool) { return true; } function() external payable {} /** PeakDeFi */ /** * @notice Returns the commission balance of `_referrer` * @return the commission balance and the received penalty, denoted in USDC */ function peakReferralCommissionBalanceOf(address _referrer) public returns (uint256 _commission) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.peakReferralCommissionBalanceOf.selector, _referrer ) ); if (!success) { return 0; } return abi.decode(result, (uint256)); } /** * @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in USDC */ function peakReferralCommissionOfAt(address _referrer, uint256 _cycle) public returns (uint256 _commission) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.peakReferralCommissionOfAt.selector, _referrer, _cycle ) ); if (!success) { return 0; } return abi.decode(result, (uint256)); } /** * @notice Redeems commission. */ function peakReferralRedeemCommission() public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.peakReferralRedeemCommission.selector) ); if (!success) { revert(); } } /** * @notice Redeems commission for a particular cycle. * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function peakReferralRedeemCommissionForCycle(uint256 _cycle) public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.peakReferralRedeemCommissionForCycle.selector, _cycle ) ); if (!success) { revert(); } } /** * @notice Changes the required PEAK stake of a new manager. Only callable by owner. * @param _newValue the new value */ function peakChangeManagerStakeRequired(uint256 _newValue) public onlyOwner { peakManagerStakeRequired = _newValue; } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./lib/ReentrancyGuard.sol"; import "./interfaces/IMiniMeToken.sol"; import "./tokens/minime/TokenController.sol"; import "./Utils.sol"; import "./PeakDeFiProxyInterface.sol"; import "./peak/reward/PeakReward.sol"; import "./peak/staking/PeakStaking.sol"; /** * @title The storage layout of PeakDeFiFund * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiStorage is Ownable, ReentrancyGuard { using SafeMath for uint256; enum CyclePhase {Intermission, Manage} enum VoteDirection {Empty, For, Against} enum Subchunk {Propose, Vote} struct Investment { address tokenAddress; uint256 cycleNumber; uint256 stake; uint256 tokenAmount; uint256 buyPrice; // token buy price in 18 decimals in USDC uint256 sellPrice; // token sell price in 18 decimals in USDC uint256 buyTime; uint256 buyCostInUSDC; bool isSold; } // Fund parameters uint256 public constant COMMISSION_RATE = 15 * (10**16); // The proportion of profits that gets distributed to RepToken holders every cycle. uint256 public constant ASSET_FEE_RATE = 1 * (10**15); // The proportion of fund balance that gets distributed to RepToken holders every cycle. uint256 public constant NEXT_PHASE_REWARD = 1 * (10**18); // Amount of RepToken rewarded to the user who calls nextPhase(). uint256 public constant COLLATERAL_RATIO_MODIFIER = 75 * (10**16); // Modifies Compound's collateral ratio, gets 2:1 from 1.5:1 ratio uint256 public constant MIN_RISK_TIME = 3 days; // Mininum risk taken to get full commissions is 9 days * reptokenBalance uint256 public constant INACTIVE_THRESHOLD = 2; // Number of inactive cycles after which a manager's RepToken balance can be burned uint256 public constant ROI_PUNISH_THRESHOLD = 1 * (10**17); // ROI worse than 10% will see punishment in stake uint256 public constant ROI_BURN_THRESHOLD = 25 * (10**16); // ROI worse than 25% will see their stake all burned uint256 public constant ROI_PUNISH_SLOPE = 6; // repROI = -(6 * absROI - 0.5) uint256 public constant ROI_PUNISH_NEG_BIAS = 5 * (10**17); // repROI = -(6 * absROI - 0.5) uint256 public constant PEAK_COMMISSION_RATE = 20 * (10**16); // The proportion of profits that gets distributed to PeakDeFi referrers every cycle. // Instance variables // Checks if the token listing initialization has been completed. bool public hasInitializedTokenListings; // Checks if the fund has been initialized bool public isInitialized; // Address of the RepToken token contract. address public controlTokenAddr; // Address of the share token contract. address public shareTokenAddr; // Address of the PeakDeFiProxy contract. address payable public proxyAddr; // Address of the CompoundOrderFactory contract. address public compoundFactoryAddr; // Address of the PeakDeFiLogic contract. address public peakdefiLogic; address public peakdefiLogic2; address public peakdefiLogic3; // Address to which the development team funding will be sent. address payable public devFundingAccount; // Address of the previous version of PeakDeFiFund. address payable public previousVersion; // The number of the current investment cycle. uint256 public cycleNumber; // The amount of funds held by the fund. uint256 public totalFundsInUSDC; // The total funds at the beginning of the current management phase uint256 public totalFundsAtManagePhaseStart; // The start time for the current investment cycle phase, in seconds since Unix epoch. uint256 public startTimeOfCyclePhase; // The proportion of PeakDeFi Shares total supply to mint and use for funding the development team. Fixed point decimal. uint256 public devFundingRate; // Total amount of commission unclaimed by managers uint256 public totalCommissionLeft; // Stores the lengths of each cycle phase in seconds. uint256[2] public phaseLengths; // The number of managers onboarded during the current cycle uint256 public managersOnboardedThisCycle; // The amount of RepToken tokens a new manager receves uint256 public newManagerRepToken; // The max number of new managers that can be onboarded in one cycle uint256 public maxNewManagersPerCycle; // The price of RepToken in USDC uint256 public reptokenPrice; // The last cycle where a user redeemed all of their remaining commission. mapping(address => uint256) internal _lastCommissionRedemption; // Marks whether a manager has redeemed their commission for a certain cycle mapping(address => mapping(uint256 => bool)) internal _hasRedeemedCommissionForCycle; // The stake-time measured risk that a manager has taken in a cycle mapping(address => mapping(uint256 => uint256)) internal _riskTakenInCycle; // In case a manager joined the fund during the current cycle, set the fallback base stake for risk threshold calculation mapping(address => uint256) internal _baseRiskStakeFallback; // List of investments of a manager in the current cycle. mapping(address => Investment[]) public userInvestments; // List of short/long orders of a manager in the current cycle. mapping(address => address payable[]) public userCompoundOrders; // Total commission to be paid for work done in a certain cycle (will be redeemed in the next cycle's Intermission) mapping(uint256 => uint256) internal _totalCommissionOfCycle; // The block number at which the Manage phase ended for a given cycle mapping(uint256 => uint256) internal _managePhaseEndBlock; // The last cycle where a manager made an investment mapping(address => uint256) internal _lastActiveCycle; // Checks if an address points to a whitelisted Kyber token. mapping(address => bool) public isKyberToken; // Checks if an address points to a whitelisted Compound token. Returns false for cUSDC and other stablecoin CompoundTokens. mapping(address => bool) public isCompoundToken; // The current cycle phase. CyclePhase public cyclePhase; // Upgrade governance related variables bool public hasFinalizedNextVersion; // Denotes if the address of the next smart contract version has been finalized address payable public nextVersion; // Address of the next version of PeakDeFiFund. // Contract instances IMiniMeToken internal cToken; IMiniMeToken internal sToken; PeakDeFiProxyInterface internal proxy; // PeakDeFi uint256 public peakReferralTotalCommissionLeft; uint256 public peakManagerStakeRequired; mapping(uint256 => uint256) internal _peakReferralTotalCommissionOfCycle; mapping(address => uint256) internal _peakReferralLastCommissionRedemption; mapping(address => mapping(uint256 => bool)) internal _peakReferralHasRedeemedCommissionForCycle; IMiniMeToken public peakReferralToken; PeakReward public peakReward; PeakStaking public peakStaking; bool public isPermissioned; mapping(address => mapping(uint256 => bool)) public hasUsedSalt; // Events event ChangedPhase( uint256 indexed _cycleNumber, uint256 indexed _newPhase, uint256 _timestamp, uint256 _totalFundsInUSDC ); event Deposit( uint256 indexed _cycleNumber, address indexed _sender, address _tokenAddress, uint256 _tokenAmount, uint256 _usdcAmount, uint256 _timestamp ); event Withdraw( uint256 indexed _cycleNumber, address indexed _sender, address _tokenAddress, uint256 _tokenAmount, uint256 _usdcAmount, uint256 _timestamp ); event CreatedInvestment( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _tokenAddress, uint256 _stakeInWeis, uint256 _buyPrice, uint256 _costUSDCAmount, uint256 _tokenAmount ); event SoldInvestment( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _tokenAddress, uint256 _receivedRepToken, uint256 _sellPrice, uint256 _earnedUSDCAmount ); event CreatedCompoundOrder( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, bool _orderType, address _tokenAddress, uint256 _stakeInWeis, uint256 _costUSDCAmount ); event SoldCompoundOrder( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, bool _orderType, address _tokenAddress, uint256 _receivedRepToken, uint256 _earnedUSDCAmount ); event RepaidCompoundOrder( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, uint256 _repaidUSDCAmount ); event CommissionPaid( uint256 indexed _cycleNumber, address indexed _sender, uint256 _commission ); event TotalCommissionPaid( uint256 indexed _cycleNumber, uint256 _totalCommissionInUSDC ); event Register( address indexed _manager, uint256 _donationInUSDC, uint256 _reptokenReceived ); event BurnDeadman(address indexed _manager, uint256 _reptokenBurned); event DeveloperInitiatedUpgrade( uint256 indexed _cycleNumber, address _candidate ); event FinalizedNextVersion( uint256 indexed _cycleNumber, address _nextVersion ); event PeakReferralCommissionPaid( uint256 indexed _cycleNumber, address indexed _sender, uint256 _commission ); event PeakReferralTotalCommissionPaid( uint256 indexed _cycleNumber, uint256 _totalCommissionInUSDC ); /* Helper functions shared by both PeakDeFiLogic & PeakDeFiFund */ function lastCommissionRedemption(address _manager) public view returns (uint256) { if (_lastCommissionRedemption[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).lastCommissionRedemption( _manager ); } return _lastCommissionRedemption[_manager]; } function hasRedeemedCommissionForCycle(address _manager, uint256 _cycle) public view returns (bool) { if (_hasRedeemedCommissionForCycle[_manager][_cycle] == false) { return previousVersion == address(0) ? false : PeakDeFiStorage(previousVersion) .hasRedeemedCommissionForCycle(_manager, _cycle); } return _hasRedeemedCommissionForCycle[_manager][_cycle]; } function riskTakenInCycle(address _manager, uint256 _cycle) public view returns (uint256) { if (_riskTakenInCycle[_manager][_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).riskTakenInCycle( _manager, _cycle ); } return _riskTakenInCycle[_manager][_cycle]; } function baseRiskStakeFallback(address _manager) public view returns (uint256) { if (_baseRiskStakeFallback[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).baseRiskStakeFallback( _manager ); } return _baseRiskStakeFallback[_manager]; } function totalCommissionOfCycle(uint256 _cycle) public view returns (uint256) { if (_totalCommissionOfCycle[_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).totalCommissionOfCycle( _cycle ); } return _totalCommissionOfCycle[_cycle]; } function managePhaseEndBlock(uint256 _cycle) public view returns (uint256) { if (_managePhaseEndBlock[_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).managePhaseEndBlock( _cycle ); } return _managePhaseEndBlock[_cycle]; } function lastActiveCycle(address _manager) public view returns (uint256) { if (_lastActiveCycle[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).lastActiveCycle(_manager); } return _lastActiveCycle[_manager]; } /** PeakDeFi */ function peakReferralLastCommissionRedemption(address _manager) public view returns (uint256) { if (_peakReferralLastCommissionRedemption[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion) .peakReferralLastCommissionRedemption(_manager); } return _peakReferralLastCommissionRedemption[_manager]; } function peakReferralHasRedeemedCommissionForCycle( address _manager, uint256 _cycle ) public view returns (bool) { if ( _peakReferralHasRedeemedCommissionForCycle[_manager][_cycle] == false ) { return previousVersion == address(0) ? false : PeakDeFiStorage(previousVersion) .peakReferralHasRedeemedCommissionForCycle( _manager, _cycle ); } return _peakReferralHasRedeemedCommissionForCycle[_manager][_cycle]; } function peakReferralTotalCommissionOfCycle(uint256 _cycle) public view returns (uint256) { if (_peakReferralTotalCommissionOfCycle[_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion) .peakReferralTotalCommissionOfCycle(_cycle); } return _peakReferralTotalCommissionOfCycle[_cycle]; } } pragma solidity 0.5.17; interface PeakDeFiProxyInterface { function peakdefiFundAddress() external view returns (address payable); function updatePeakDeFiFundAddress() external; } pragma solidity 0.5.17; import "./PeakDeFiFund.sol"; contract PeakDeFiProxy { address payable public peakdefiFundAddress; event UpdatedFundAddress(address payable _newFundAddr); constructor(address payable _fundAddr) public { peakdefiFundAddress = _fundAddr; emit UpdatedFundAddress(_fundAddr); } function updatePeakDeFiFundAddress() public { require(msg.sender == peakdefiFundAddress, "Sender not PeakDeFiFund"); address payable nextVersion = PeakDeFiFund(peakdefiFundAddress) .nextVersion(); require(nextVersion != address(0), "Next version can't be empty"); peakdefiFundAddress = nextVersion; emit UpdatedFundAddress(peakdefiFundAddress); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./PeakDeFiStorage.sol"; import "./derivatives/CompoundOrderFactory.sol"; /** * @title Part of the functions for PeakDeFiFund * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiLogic is PeakDeFiStorage, Utils(address(0), address(0), address(0)) { /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); if (cyclePhase == CyclePhase.Intermission) { require(isInitialized); } _; } /** * @notice Returns the length of the user's investments array. * @return length of the user's investments array */ function investmentsCount(address _userAddr) public view returns (uint256 _count) { return userInvestments[_userAddr].length; } /** * @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles * @param _deadman the manager whose RepToken balance will be burned */ function burnDeadman(address _deadman) public nonReentrant during(CyclePhase.Intermission) { require(_deadman != address(this)); require( cycleNumber.sub(lastActiveCycle(_deadman)) > INACTIVE_THRESHOLD ); uint256 balance = cToken.balanceOf(_deadman); require(cToken.destroyTokens(_deadman, balance)); emit BurnDeadman(_deadman, balance); } /** * @notice Creates a new investment for an ERC20 token. Backwards compatible. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade */ function createInvestment( address _tokenAddress, uint256 _stake, uint256 _maxPrice ) public { bytes memory nil; createInvestmentV2( msg.sender, _tokenAddress, _stake, _maxPrice, nil, true ); } function createInvestmentWithSignature( address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.createInvestmentWithSignature.selector, abi.encode( _tokenAddress, _stake, _maxPrice, _calldata, _useKyber ), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.createInvestmentV2( _manager, _tokenAddress, _stake, _maxPrice, _calldata, _useKyber ); } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. Backwards compatible. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAsset( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice ) public { bytes memory nil; sellInvestmentAssetV2( msg.sender, _investmentId, _tokenAmount, _minPrice, nil, true ); } function sellInvestmentWithSignature( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.sellInvestmentWithSignature.selector, abi.encode( _investmentId, _tokenAmount, _minPrice, _calldata, _useKyber ), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.sellInvestmentAssetV2( _manager, _investmentId, _tokenAmount, _minPrice, _calldata, _useKyber ); } /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade * @param _calldata calldata for 1inch trading * @param _useKyber true for Kyber Network, false for 1inch */ function createInvestmentV2( address _sender, address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes memory _calldata, bool _useKyber ) public during(CyclePhase.Manage) nonReentrant isValidToken(_tokenAddress) { require(msg.sender == _sender || msg.sender == address(this)); require(_stake > 0); require(isKyberToken[_tokenAddress]); // Verify user peak stake uint256 peakStake = peakStaking.userStakeAmount(_sender); require(peakStake >= peakManagerStakeRequired); // Collect stake require(cToken.generateTokens(address(this), _stake)); require(cToken.destroyTokens(_sender, _stake)); // Add investment to list userInvestments[_sender].push( Investment({ tokenAddress: _tokenAddress, cycleNumber: cycleNumber, stake: _stake, tokenAmount: 0, buyPrice: 0, sellPrice: 0, buyTime: now, buyCostInUSDC: 0, isSold: false }) ); // Invest uint256 investmentId = investmentsCount(_sender).sub(1); __handleInvestment( _sender, investmentId, 0, _maxPrice, true, _calldata, _useKyber ); // Update last active cycle _lastActiveCycle[_sender] = cycleNumber; // Emit event __emitCreatedInvestmentEvent(_sender, investmentId); } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAssetV2( address _sender, uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes memory _calldata, bool _useKyber ) public nonReentrant during(CyclePhase.Manage) { require(msg.sender == _sender || msg.sender == address(this)); Investment storage investment = userInvestments[_sender][_investmentId]; require( investment.buyPrice > 0 && investment.cycleNumber == cycleNumber && !investment.isSold ); require(_tokenAmount > 0 && _tokenAmount <= investment.tokenAmount); // Create new investment for leftover tokens bool isPartialSell = false; uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div( investment.tokenAmount ); if (_tokenAmount != investment.tokenAmount) { isPartialSell = true; __createInvestmentForLeftovers( _sender, _investmentId, _tokenAmount ); __emitCreatedInvestmentEvent( _sender, investmentsCount(_sender).sub(1) ); } // Update investment info investment.isSold = true; // Sell asset ( uint256 actualDestAmount, uint256 actualSrcAmount ) = __handleInvestment( _sender, _investmentId, _minPrice, uint256(-1), false, _calldata, _useKyber ); __sellInvestmentUpdate( _sender, _investmentId, stakeOfSoldTokens, actualDestAmount ); } function __sellInvestmentUpdate( address _sender, uint256 _investmentId, uint256 stakeOfSoldTokens, uint256 actualDestAmount ) internal { Investment storage investment = userInvestments[_sender][_investmentId]; // Return staked RepToken uint256 receiveRepTokenAmount = getReceiveRepTokenAmount( stakeOfSoldTokens, investment.sellPrice, investment.buyPrice ); __returnStake(receiveRepTokenAmount, stakeOfSoldTokens); // Record risk taken in investment __recordRisk(_sender, investment.stake, investment.buyTime); // Update total funds totalFundsInUSDC = totalFundsInUSDC.sub(investment.buyCostInUSDC).add( actualDestAmount ); // Emit event __emitSoldInvestmentEvent( _sender, _investmentId, receiveRepTokenAmount, actualDestAmount ); } function __emitSoldInvestmentEvent( address _sender, uint256 _investmentId, uint256 _receiveRepTokenAmount, uint256 _actualDestAmount ) internal { Investment storage investment = userInvestments[_sender][_investmentId]; emit SoldInvestment( cycleNumber, _sender, _investmentId, investment.tokenAddress, _receiveRepTokenAmount, investment.sellPrice, _actualDestAmount ); } function __createInvestmentForLeftovers( address _sender, uint256 _investmentId, uint256 _tokenAmount ) internal { Investment storage investment = userInvestments[_sender][_investmentId]; uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div( investment.tokenAmount ); // calculate the part of original USDC cost attributed to the sold tokens uint256 soldBuyCostInUSDC = investment .buyCostInUSDC .mul(_tokenAmount) .div(investment.tokenAmount); userInvestments[_sender].push( Investment({ tokenAddress: investment.tokenAddress, cycleNumber: cycleNumber, stake: investment.stake.sub(stakeOfSoldTokens), tokenAmount: investment.tokenAmount.sub(_tokenAmount), buyPrice: investment.buyPrice, sellPrice: 0, buyTime: investment.buyTime, buyCostInUSDC: investment.buyCostInUSDC.sub(soldBuyCostInUSDC), isSold: false }) ); // update the investment object being sold investment.tokenAmount = _tokenAmount; investment.stake = stakeOfSoldTokens; investment.buyCostInUSDC = soldBuyCostInUSDC; } function __emitCreatedInvestmentEvent(address _sender, uint256 _id) internal { Investment storage investment = userInvestments[_sender][_id]; emit CreatedInvestment( cycleNumber, _sender, _id, investment.tokenAddress, investment.stake, investment.buyPrice, investment.buyCostInUSDC, investment.tokenAmount ); } function createCompoundOrderWithSignature( bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.createCompoundOrderWithSignature.selector, abi.encode( _orderType, _tokenAddress, _stake, _minPrice, _maxPrice ), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.createCompoundOrder( _manager, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice ); } function sellCompoundOrderWithSignature( uint256 _orderId, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.sellCompoundOrderWithSignature.selector, abi.encode(_orderId, _minPrice, _maxPrice), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.sellCompoundOrder(_manager, _orderId, _minPrice, _maxPrice); } function repayCompoundOrderWithSignature( uint256 _orderId, uint256 _repayAmountInUSDC, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.repayCompoundOrderWithSignature.selector, abi.encode(_orderId, _repayAmountInUSDC), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.repayCompoundOrder(_manager, _orderId, _repayAmountInUSDC); } /** * @notice Creates a new Compound order to either short or leverage long a token. * @param _orderType true for a short order, false for a levarage long order * @param _tokenAddress address of the Compound token to be traded * @param _stake amount of RepTokens to be staked * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function createCompoundOrder( address _sender, bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) public during(CyclePhase.Manage) nonReentrant isValidToken(_tokenAddress) { require(msg.sender == _sender || msg.sender == address(this)); require(_minPrice <= _maxPrice); require(_stake > 0); require(isCompoundToken[_tokenAddress]); // Verify user peak stake uint256 peakStake = peakStaking.userStakeAmount(_sender); require(peakStake >= peakManagerStakeRequired); // Collect stake require(cToken.generateTokens(address(this), _stake)); require(cToken.destroyTokens(_sender, _stake)); // Create compound order and execute uint256 collateralAmountInUSDC = totalFundsInUSDC.mul(_stake).div( cToken.totalSupply() ); CompoundOrder order = __createCompoundOrder( _orderType, _tokenAddress, _stake, collateralAmountInUSDC ); usdc.safeApprove(address(order), 0); usdc.safeApprove(address(order), collateralAmountInUSDC); order.executeOrder(_minPrice, _maxPrice); // Add order to list userCompoundOrders[_sender].push(address(order)); // Update last active cycle _lastActiveCycle[_sender] = cycleNumber; __emitCreatedCompoundOrderEvent( _sender, address(order), _orderType, _tokenAddress, _stake, collateralAmountInUSDC ); } function __emitCreatedCompoundOrderEvent( address _sender, address order, bool _orderType, address _tokenAddress, uint256 _stake, uint256 collateralAmountInUSDC ) internal { // Emit event emit CreatedCompoundOrder( cycleNumber, _sender, userCompoundOrders[_sender].length - 1, address(order), _orderType, _tokenAddress, _stake, collateralAmountInUSDC ); } /** * @notice Sells a compound order * @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender]) * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function sellCompoundOrder( address _sender, uint256 _orderId, uint256 _minPrice, uint256 _maxPrice ) public during(CyclePhase.Manage) nonReentrant { require(msg.sender == _sender || msg.sender == address(this)); // Load order info require(userCompoundOrders[_sender][_orderId] != address(0)); CompoundOrder order = CompoundOrder( userCompoundOrders[_sender][_orderId] ); require(order.isSold() == false && order.cycleNumber() == cycleNumber); // Sell order (uint256 inputAmount, uint256 outputAmount) = order.sellOrder( _minPrice, _maxPrice ); // Return staked RepToken uint256 stake = order.stake(); uint256 receiveRepTokenAmount = getReceiveRepTokenAmount( stake, outputAmount, inputAmount ); __returnStake(receiveRepTokenAmount, stake); // Record risk taken __recordRisk(_sender, stake, order.buyTime()); // Update total funds totalFundsInUSDC = totalFundsInUSDC.sub(inputAmount).add(outputAmount); // Emit event emit SoldCompoundOrder( cycleNumber, _sender, userCompoundOrders[_sender].length - 1, address(order), order.orderType(), order.compoundTokenAddr(), receiveRepTokenAmount, outputAmount ); } /** * @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold. * @param _orderId the ID of the Compound order * @param _repayAmountInUSDC amount of USDC to use for repaying debt */ function repayCompoundOrder( address _sender, uint256 _orderId, uint256 _repayAmountInUSDC ) public during(CyclePhase.Manage) nonReentrant { require(msg.sender == _sender || msg.sender == address(this)); // Load order info require(userCompoundOrders[_sender][_orderId] != address(0)); CompoundOrder order = CompoundOrder( userCompoundOrders[_sender][_orderId] ); require(order.isSold() == false && order.cycleNumber() == cycleNumber); // Repay loan order.repayLoan(_repayAmountInUSDC); // Emit event emit RepaidCompoundOrder( cycleNumber, _sender, userCompoundOrders[_sender].length - 1, address(order), _repayAmountInUSDC ); } function emergencyExitCompoundTokens( address _sender, uint256 _orderId, address _tokenAddr, address _receiver ) public during(CyclePhase.Intermission) nonReentrant { CompoundOrder order = CompoundOrder(userCompoundOrders[_sender][_orderId]); order.emergencyExitTokens(_tokenAddr, _receiver); } function getReceiveRepTokenAmount( uint256 stake, uint256 output, uint256 input ) public pure returns (uint256 _amount) { if (output >= input) { // positive ROI, simply return stake * (1 + ROI) return stake.mul(output).div(input); } else { // negative ROI uint256 absROI = input.sub(output).mul(PRECISION).div(input); if (absROI <= ROI_PUNISH_THRESHOLD) { // ROI better than -10%, no punishment return stake.mul(output).div(input); } else if ( absROI > ROI_PUNISH_THRESHOLD && absROI < ROI_BURN_THRESHOLD ) { // ROI between -10% and -25%, punish // return stake * (1 + roiWithPunishment) = stake * (1 + (-(6 * absROI - 0.5))) return stake .mul( PRECISION.sub( ROI_PUNISH_SLOPE.mul(absROI).sub( ROI_PUNISH_NEG_BIAS ) ) ) .div(PRECISION); } else { // ROI greater than 25%, burn all stake return 0; } } } /** * @notice Handles and investment by doing the necessary trades using __kyberTrade() or Fulcrum trading * @param _investmentId the ID of the investment to be handled * @param _minPrice the minimum price for the trade * @param _maxPrice the maximum price for the trade * @param _buy whether to buy or sell the given investment * @param _calldata calldata for 1inch trading * @param _useKyber true for Kyber Network, false for 1inch */ function __handleInvestment( address _sender, uint256 _investmentId, uint256 _minPrice, uint256 _maxPrice, bool _buy, bytes memory _calldata, bool _useKyber ) internal returns (uint256 _actualDestAmount, uint256 _actualSrcAmount) { Investment storage investment = userInvestments[_sender][_investmentId]; address token = investment.tokenAddress; // Basic trading uint256 dInS; // price of dest token denominated in src token uint256 sInD; // price of src token denominated in dest token if (_buy) { if (_useKyber) { ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __kyberTrade( usdc, totalFundsInUSDC.mul(investment.stake).div( cToken.totalSupply() ), ERC20Detailed(token) ); } else { // 1inch trading ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __oneInchTrade( usdc, totalFundsInUSDC.mul(investment.stake).div( cToken.totalSupply() ), ERC20Detailed(token), _calldata ); } require(_minPrice <= dInS && dInS <= _maxPrice); investment.buyPrice = dInS; investment.tokenAmount = _actualDestAmount; investment.buyCostInUSDC = _actualSrcAmount; } else { if (_useKyber) { ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __kyberTrade( ERC20Detailed(token), investment.tokenAmount, usdc ); } else { ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __oneInchTrade( ERC20Detailed(token), investment.tokenAmount, usdc, _calldata ); } require(_minPrice <= sInD && sInD <= _maxPrice); investment.sellPrice = sInD; } } /** * @notice Separated from createCompoundOrder() to avoid stack too deep error */ function __createCompoundOrder( bool _orderType, // True for shorting, false for longing address _tokenAddress, uint256 _stake, uint256 _collateralAmountInUSDC ) internal returns (CompoundOrder) { CompoundOrderFactory factory = CompoundOrderFactory( compoundFactoryAddr ); uint256 loanAmountInUSDC = _collateralAmountInUSDC .mul(COLLATERAL_RATIO_MODIFIER) .div(PRECISION) .mul(factory.getMarketCollateralFactor(_tokenAddress)) .div(PRECISION); CompoundOrder order = factory.createOrder( _tokenAddress, cycleNumber, _stake, _collateralAmountInUSDC, loanAmountInUSDC, _orderType ); return order; } /** * @notice Returns stake to manager after investment is sold, including reward/penalty based on performance */ function __returnStake(uint256 _receiveRepTokenAmount, uint256 _stake) internal { require(cToken.destroyTokens(address(this), _stake)); require(cToken.generateTokens(msg.sender, _receiveRepTokenAmount)); } /** * @notice Records risk taken in a trade based on stake and time of investment */ function __recordRisk( address _sender, uint256 _stake, uint256 _buyTime ) internal { _riskTakenInCycle[_sender][cycleNumber] = riskTakenInCycle( _sender, cycleNumber ) .add(_stake.mul(now.sub(_buyTime))); } } pragma solidity ^0.5.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity 0.5.17; import "./PeakDeFiStorage.sol"; import "./derivatives/CompoundOrderFactory.sol"; import "@nomiclabs/buidler/console.sol"; /** * @title Part of the functions for PeakDeFiFund * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiLogic2 is PeakDeFiStorage, Utils(address(0), address(0), address(0)) { /** * @notice Passes if the fund has not finalized the next smart contract to upgrade to */ modifier notReadyForUpgrade { require(hasFinalizedNextVersion == false); _; } /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); if (cyclePhase == CyclePhase.Intermission) { require(isInitialized); } _; } /** * Deposit & Withdraw */ function depositEther(address _referrer) public payable { bytes memory nil; depositEtherAdvanced(true, nil, _referrer); } /** * @notice Deposit Ether into the fund. Ether will be converted into USDC. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading * @param _referrer the referrer's address */ function depositEtherAdvanced( bool _useKyber, bytes memory _calldata, address _referrer ) public payable nonReentrant notReadyForUpgrade { // Buy USDC with ETH uint256 actualUSDCDeposited; uint256 actualETHDeposited; if (_useKyber) { (, , actualUSDCDeposited, actualETHDeposited) = __kyberTrade( ETH_TOKEN_ADDRESS, msg.value, usdc ); } else { (, , actualUSDCDeposited, actualETHDeposited) = __oneInchTrade( ETH_TOKEN_ADDRESS, msg.value, usdc, _calldata ); } // Send back leftover ETH uint256 leftOverETH = msg.value.sub(actualETHDeposited); if (leftOverETH > 0) { msg.sender.transfer(leftOverETH); } // Register investment __deposit(actualUSDCDeposited, _referrer); // Emit event emit Deposit( cycleNumber, msg.sender, address(ETH_TOKEN_ADDRESS), actualETHDeposited, actualUSDCDeposited, now ); } /** * @notice Deposit USDC Stablecoin into the fund. * @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount. * @param _referrer the referrer's address */ function depositUSDC(uint256 _usdcAmount, address _referrer) public nonReentrant notReadyForUpgrade { usdc.safeTransferFrom(msg.sender, address(this), _usdcAmount); // Register investment __deposit(_usdcAmount, _referrer); // Emit event emit Deposit( cycleNumber, msg.sender, USDC_ADDR, _usdcAmount, _usdcAmount, now ); } function depositToken( address _tokenAddr, uint256 _tokenAmount, address _referrer ) public { bytes memory nil; depositTokenAdvanced(_tokenAddr, _tokenAmount, true, nil, _referrer); } /** * @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC. * @param _tokenAddr the address of the token to be deposited * @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading * @param _referrer the referrer's address */ function depositTokenAdvanced( address _tokenAddr, uint256 _tokenAmount, bool _useKyber, bytes memory _calldata, address _referrer ) public nonReentrant notReadyForUpgrade isValidToken(_tokenAddr) { require( _tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS) ); ERC20Detailed token = ERC20Detailed(_tokenAddr); token.safeTransferFrom(msg.sender, address(this), _tokenAmount); // Convert token into USDC uint256 actualUSDCDeposited; uint256 actualTokenDeposited; if (_useKyber) { (, , actualUSDCDeposited, actualTokenDeposited) = __kyberTrade( token, _tokenAmount, usdc ); } else { (, , actualUSDCDeposited, actualTokenDeposited) = __oneInchTrade( token, _tokenAmount, usdc, _calldata ); } // Give back leftover tokens uint256 leftOverTokens = _tokenAmount.sub(actualTokenDeposited); if (leftOverTokens > 0) { token.safeTransfer(msg.sender, leftOverTokens); } // Register investment __deposit(actualUSDCDeposited, _referrer); // Emit event emit Deposit( cycleNumber, msg.sender, _tokenAddr, actualTokenDeposited, actualUSDCDeposited, now ); } function withdrawEther(uint256 _amountInUSDC) external { bytes memory nil; withdrawEtherAdvanced(_amountInUSDC, true, nil); } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading */ function withdrawEtherAdvanced( uint256 _amountInUSDC, bool _useKyber, bytes memory _calldata ) public nonReentrant during(CyclePhase.Intermission) { // Buy ETH uint256 actualETHWithdrawn; uint256 actualUSDCWithdrawn; if (_useKyber) { (, , actualETHWithdrawn, actualUSDCWithdrawn) = __kyberTrade( usdc, _amountInUSDC, ETH_TOKEN_ADDRESS ); } else { (, , actualETHWithdrawn, actualUSDCWithdrawn) = __oneInchTrade( usdc, _amountInUSDC, ETH_TOKEN_ADDRESS, _calldata ); } __withdraw(actualUSDCWithdrawn); // Transfer Ether to user msg.sender.transfer(actualETHWithdrawn); // Emit event emit Withdraw( cycleNumber, msg.sender, address(ETH_TOKEN_ADDRESS), actualETHWithdrawn, actualUSDCWithdrawn, now ); } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawUSDC(uint256 _amountInUSDC) external nonReentrant during(CyclePhase.Intermission) { __withdraw(_amountInUSDC); // Transfer USDC to user usdc.safeTransfer(msg.sender, _amountInUSDC); // Emit event emit Withdraw( cycleNumber, msg.sender, USDC_ADDR, _amountInUSDC, _amountInUSDC, now ); } function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external { bytes memory nil; withdrawTokenAdvanced(_tokenAddr, _amountInUSDC, true, nil); } /** * @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network. * @param _tokenAddr the address of the token to be withdrawn into the caller's account * @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading */ function withdrawTokenAdvanced( address _tokenAddr, uint256 _amountInUSDC, bool _useKyber, bytes memory _calldata ) public during(CyclePhase.Intermission) nonReentrant isValidToken(_tokenAddr) { require( _tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS) ); ERC20Detailed token = ERC20Detailed(_tokenAddr); // Convert USDC into desired tokens uint256 actualTokenWithdrawn; uint256 actualUSDCWithdrawn; if (_useKyber) { (, , actualTokenWithdrawn, actualUSDCWithdrawn) = __kyberTrade( usdc, _amountInUSDC, token ); } else { (, , actualTokenWithdrawn, actualUSDCWithdrawn) = __oneInchTrade( usdc, _amountInUSDC, token, _calldata ); } __withdraw(actualUSDCWithdrawn); // Transfer tokens to user token.safeTransfer(msg.sender, actualTokenWithdrawn); // Emit event emit Withdraw( cycleNumber, msg.sender, _tokenAddr, actualTokenWithdrawn, actualUSDCWithdrawn, now ); } /** * Manager registration */ /** * @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithUSDC() public during(CyclePhase.Intermission) nonReentrant { require(!isPermissioned); require(managersOnboardedThisCycle < maxNewManagersPerCycle); managersOnboardedThisCycle = managersOnboardedThisCycle.add(1); uint256 peakStake = peakStaking.userStakeAmount(msg.sender); require(peakStake >= peakManagerStakeRequired); uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION); usdc.safeTransferFrom(msg.sender, address(this), donationInUSDC); __register(donationInUSDC); } /** * @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithETH() public payable during(CyclePhase.Intermission) nonReentrant { require(!isPermissioned); require(managersOnboardedThisCycle < maxNewManagersPerCycle); managersOnboardedThisCycle = managersOnboardedThisCycle.add(1); uint256 peakStake = peakStaking.userStakeAmount(msg.sender); require(peakStake >= peakManagerStakeRequired); uint256 receivedUSDC; // trade ETH for USDC (, , receivedUSDC, ) = __kyberTrade(ETH_TOKEN_ADDRESS, msg.value, usdc); // if USDC value is greater than the amount required, return excess USDC to msg.sender uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION); if (receivedUSDC > donationInUSDC) { usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC)); receivedUSDC = donationInUSDC; } // register new manager __register(receivedUSDC); } /** * @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. * @param _token the token to be used for payment * @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals */ function registerWithToken(address _token, uint256 _donationInTokens) public during(CyclePhase.Intermission) nonReentrant { require(!isPermissioned); require(managersOnboardedThisCycle < maxNewManagersPerCycle); managersOnboardedThisCycle = managersOnboardedThisCycle.add(1); uint256 peakStake = peakStaking.userStakeAmount(msg.sender); require(peakStake >= peakManagerStakeRequired); require( _token != address(0) && _token != address(ETH_TOKEN_ADDRESS) && _token != USDC_ADDR ); ERC20Detailed token = ERC20Detailed(_token); require(token.totalSupply() > 0); token.safeTransferFrom(msg.sender, address(this), _donationInTokens); uint256 receivedUSDC; (, , receivedUSDC, ) = __kyberTrade(token, _donationInTokens, usdc); // if USDC value is greater than the amount required, return excess USDC to msg.sender uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION); if (receivedUSDC > donationInUSDC) { usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC)); receivedUSDC = donationInUSDC; } // register new manager __register(receivedUSDC); } function peakAdminRegisterManager(address _manager, uint256 _reptokenAmount) public during(CyclePhase.Intermission) nonReentrant onlyOwner { require(isPermissioned); // mint REP for msg.sender require(cToken.generateTokens(_manager, _reptokenAmount)); // Set risk fallback base stake _baseRiskStakeFallback[_manager] = _baseRiskStakeFallback[_manager].add( _reptokenAmount ); // Set last active cycle for msg.sender to be the current cycle _lastActiveCycle[_manager] = cycleNumber; // emit events emit Register(_manager, 0, _reptokenAmount); } /** * @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _tokenAddr address of the token to be sold * @param _calldata the 1inch trade call data */ function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata) external during(CyclePhase.Intermission) nonReentrant isValidToken(_tokenAddr) { ERC20Detailed token = ERC20Detailed(_tokenAddr); (, , uint256 actualUSDCReceived, ) = __oneInchTrade( token, getBalance(token, address(this)), usdc, _calldata ); totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived); } /** * @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _orderAddress address of the CompoundOrder to be sold */ function sellLeftoverCompoundOrder(address payable _orderAddress) public during(CyclePhase.Intermission) nonReentrant { // Load order info require(_orderAddress != address(0)); CompoundOrder order = CompoundOrder(_orderAddress); require(order.isSold() == false && order.cycleNumber() < cycleNumber); // Sell short order // Not using outputAmount returned by order.sellOrder() because _orderAddress could point to a malicious contract uint256 beforeUSDCBalance = usdc.balanceOf(address(this)); order.sellOrder(0, MAX_QTY); uint256 actualUSDCReceived = usdc.balanceOf(address(this)).sub( beforeUSDCBalance ); totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived); } /** * @notice Registers `msg.sender` as a manager. * @param _donationInUSDC the amount of USDC to be used for registration */ function __register(uint256 _donationInUSDC) internal { require( cToken.balanceOf(msg.sender) == 0 && userInvestments[msg.sender].length == 0 && userCompoundOrders[msg.sender].length == 0 ); // each address can only join once // mint REP for msg.sender uint256 repAmount = _donationInUSDC.mul(PRECISION).div(reptokenPrice); require(cToken.generateTokens(msg.sender, repAmount)); // Set risk fallback base stake _baseRiskStakeFallback[msg.sender] = repAmount; // Set last active cycle for msg.sender to be the current cycle _lastActiveCycle[msg.sender] = cycleNumber; // keep USDC in the fund totalFundsInUSDC = totalFundsInUSDC.add(_donationInUSDC); // emit events emit Register(msg.sender, _donationInUSDC, repAmount); } /** * @notice Handles deposits by minting PeakDeFi Shares & updating total funds. * @param _depositUSDCAmount The amount of the deposit in USDC * @param _referrer The deposit referrer */ function __deposit(uint256 _depositUSDCAmount, address _referrer) internal { // Register investment and give shares uint256 shareAmount; if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) { uint256 usdcDecimals = getDecimals(usdc); shareAmount = _depositUSDCAmount.mul(PRECISION).div(10**usdcDecimals); } else { shareAmount = _depositUSDCAmount.mul(sToken.totalSupply()).div( totalFundsInUSDC ); } require(sToken.generateTokens(msg.sender, shareAmount)); totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount); totalFundsAtManagePhaseStart = totalFundsAtManagePhaseStart.add( _depositUSDCAmount ); // Handle peakReferralToken if (peakReward.canRefer(msg.sender, _referrer)) { peakReward.refer(msg.sender, _referrer); } address actualReferrer = peakReward.referrerOf(msg.sender); if (actualReferrer != address(0)) { require( peakReferralToken.generateTokens(actualReferrer, shareAmount) ); } } /** * @notice Handles deposits by burning PeakDeFi Shares & updating total funds. * @param _withdrawUSDCAmount The amount of the withdrawal in USDC */ function __withdraw(uint256 _withdrawUSDCAmount) internal { // Burn Shares uint256 shareAmount = _withdrawUSDCAmount.mul(sToken.totalSupply()).div( totalFundsInUSDC ); require(sToken.destroyTokens(msg.sender, shareAmount)); totalFundsInUSDC = totalFundsInUSDC.sub(_withdrawUSDCAmount); // Handle peakReferralToken address actualReferrer = peakReward.referrerOf(msg.sender); if (actualReferrer != address(0)) { uint256 balance = peakReferralToken.balanceOf(actualReferrer); uint256 burnReferralTokenAmount = shareAmount > balance ? balance : shareAmount; require( peakReferralToken.destroyTokens( actualReferrer, burnReferralTokenAmount ) ); } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.8.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } pragma solidity 0.5.17; import "./PeakDeFiStorage.sol"; contract PeakDeFiLogic3 is PeakDeFiStorage, Utils(address(0), address(0), address(0)) { /** * @notice Passes if the fund has not finalized the next smart contract to upgrade to */ modifier notReadyForUpgrade { require(hasFinalizedNextVersion == false); _; } /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); if (cyclePhase == CyclePhase.Intermission) { require(isInitialized); } _; } /** * Next phase transition handler * @notice Moves the fund to the next phase in the investment cycle. */ function nextPhase() public nonReentrant { require( now >= startTimeOfCyclePhase.add(phaseLengths[uint256(cyclePhase)]) ); if (isInitialized == false) { // first cycle of this smart contract deployment // check whether ready for starting cycle isInitialized = true; require(proxyAddr != address(0)); // has initialized proxy require(proxy.peakdefiFundAddress() == address(this)); // upgrade complete require(hasInitializedTokenListings); // has initialized token listings // execute initialization function __init(); require( previousVersion == address(0) || (previousVersion != address(0) && getBalance(usdc, address(this)) > 0) ); // has transfered assets from previous version } else { // normal phase changing if (cyclePhase == CyclePhase.Intermission) { require(hasFinalizedNextVersion == false); // Shouldn't progress to next phase if upgrading // Update total funds at management phase's beginning totalFundsAtManagePhaseStart = totalFundsInUSDC; // reset number of managers onboarded managersOnboardedThisCycle = 0; } else if (cyclePhase == CyclePhase.Manage) { // Burn any RepToken left in PeakDeFiFund's account require( cToken.destroyTokens( address(this), cToken.balanceOf(address(this)) ) ); // Pay out commissions and fees uint256 profit = 0; uint256 usdcBalanceAtManagePhaseStart = totalFundsAtManagePhaseStart.add(totalCommissionLeft); if ( getBalance(usdc, address(this)) > usdcBalanceAtManagePhaseStart ) { profit = getBalance(usdc, address(this)).sub( usdcBalanceAtManagePhaseStart ); } totalFundsInUSDC = getBalance(usdc, address(this)) .sub(totalCommissionLeft) .sub(peakReferralTotalCommissionLeft); // Calculate manager commissions uint256 commissionThisCycle = COMMISSION_RATE .mul(profit) .add(ASSET_FEE_RATE.mul(totalFundsInUSDC)) .div(PRECISION); _totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle( cycleNumber ) .add(commissionThisCycle); // account for penalties totalCommissionLeft = totalCommissionLeft.add( commissionThisCycle ); // Calculate referrer commissions uint256 peakReferralCommissionThisCycle = PEAK_COMMISSION_RATE .mul(profit) .mul(peakReferralToken.totalSupply()) .div(sToken.totalSupply()) .div(PRECISION); _peakReferralTotalCommissionOfCycle[cycleNumber] = peakReferralTotalCommissionOfCycle( cycleNumber ) .add(peakReferralCommissionThisCycle); peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft .add(peakReferralCommissionThisCycle); totalFundsInUSDC = getBalance(usdc, address(this)) .sub(totalCommissionLeft) .sub(peakReferralTotalCommissionLeft); // Give the developer PeakDeFi shares inflation funding uint256 devFunding = devFundingRate .mul(sToken.totalSupply()) .div(PRECISION); require(sToken.generateTokens(devFundingAccount, devFunding)); // Emit event emit TotalCommissionPaid( cycleNumber, totalCommissionOfCycle(cycleNumber) ); emit PeakReferralTotalCommissionPaid( cycleNumber, peakReferralTotalCommissionOfCycle(cycleNumber) ); _managePhaseEndBlock[cycleNumber] = block.number; // Clear/update upgrade related data if (nextVersion == address(this)) { // The developer proposed a candidate, but the managers decide to not upgrade at all // Reset upgrade process delete nextVersion; delete hasFinalizedNextVersion; } if (nextVersion != address(0)) { hasFinalizedNextVersion = true; emit FinalizedNextVersion(cycleNumber, nextVersion); } // Start new cycle cycleNumber = cycleNumber.add(1); } cyclePhase = CyclePhase(addmod(uint256(cyclePhase), 1, 2)); } startTimeOfCyclePhase = now; // Reward caller if they're a manager if (cToken.balanceOf(msg.sender) > 0) { require(cToken.generateTokens(msg.sender, NEXT_PHASE_REWARD)); } emit ChangedPhase( cycleNumber, uint256(cyclePhase), now, totalFundsInUSDC ); } /** * @notice Initializes several important variables after smart contract upgrade */ function __init() internal { _managePhaseEndBlock[cycleNumber.sub(1)] = block.number; // load values from previous version totalCommissionLeft = previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).totalCommissionLeft(); totalFundsInUSDC = getBalance(usdc, address(this)).sub( totalCommissionLeft ); } /** * Upgrading functions */ /** * @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to. * The developer may change the candidate during the Intermission phase. * @param _candidate the address of the candidate smart contract * @return True if successfully changed candidate, false otherwise. */ function developerInitiateUpgrade(address payable _candidate) public onlyOwner notReadyForUpgrade during(CyclePhase.Intermission) nonReentrant returns (bool _success) { if (_candidate == address(0) || _candidate == address(this)) { return false; } nextVersion = _candidate; emit DeveloperInitiatedUpgrade(cycleNumber, _candidate); return true; } /** Commission functions */ /** * @notice Returns the commission balance of `_manager` * @return the commission balance and the received penalty, denoted in USDC */ function commissionBalanceOf(address _manager) public view returns (uint256 _commission, uint256 _penalty) { if (lastCommissionRedemption(_manager) >= cycleNumber) { return (0, 0); } uint256 cycle = lastCommissionRedemption(_manager) > 0 ? lastCommissionRedemption(_manager) : 1; uint256 cycleCommission; uint256 cyclePenalty; for (; cycle < cycleNumber; cycle++) { (cycleCommission, cyclePenalty) = commissionOfAt(_manager, cycle); _commission = _commission.add(cycleCommission); _penalty = _penalty.add(cyclePenalty); } } /** * @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in USDC */ function commissionOfAt(address _manager, uint256 _cycle) public view returns (uint256 _commission, uint256 _penalty) { if (hasRedeemedCommissionForCycle(_manager, _cycle)) { return (0, 0); } // take risk into account uint256 baseRepTokenBalance = cToken.balanceOfAt( _manager, managePhaseEndBlock(_cycle.sub(1)) ); uint256 baseStake = baseRepTokenBalance == 0 ? baseRiskStakeFallback(_manager) : baseRepTokenBalance; if (baseRepTokenBalance == 0 && baseRiskStakeFallback(_manager) == 0) { return (0, 0); } uint256 riskTakenProportion = riskTakenInCycle(_manager, _cycle) .mul(PRECISION) .div(baseStake.mul(MIN_RISK_TIME)); // risk / threshold riskTakenProportion = riskTakenProportion > PRECISION ? PRECISION : riskTakenProportion; // max proportion is 1 uint256 fullCommission = totalCommissionOfCycle(_cycle) .mul(cToken.balanceOfAt(_manager, managePhaseEndBlock(_cycle))) .div(cToken.totalSupplyAt(managePhaseEndBlock(_cycle))); _commission = fullCommission.mul(riskTakenProportion).div(PRECISION); _penalty = fullCommission.sub(_commission); } /** * @notice Redeems commission. */ function redeemCommission(bool _inShares) public during(CyclePhase.Intermission) nonReentrant { uint256 commission = __redeemCommission(); if (_inShares) { // Deposit commission into fund __deposit(commission); // Emit deposit event emit Deposit( cycleNumber, msg.sender, USDC_ADDR, commission, commission, now ); } else { // Transfer the commission in USDC usdc.safeTransfer(msg.sender, commission); } } /** * @notice Redeems commission for a particular cycle. * @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function redeemCommissionForCycle(bool _inShares, uint256 _cycle) public during(CyclePhase.Intermission) nonReentrant { require(_cycle < cycleNumber); uint256 commission = __redeemCommissionForCycle(_cycle); if (_inShares) { // Deposit commission into fund __deposit(commission); // Emit deposit event emit Deposit( cycleNumber, msg.sender, USDC_ADDR, commission, commission, now ); } else { // Transfer the commission in USDC usdc.safeTransfer(msg.sender, commission); } } /** * @notice Redeems the commission for all previous cycles. Updates the related variables. * @return the amount of commission to be redeemed */ function __redeemCommission() internal returns (uint256 _commission) { require(lastCommissionRedemption(msg.sender) < cycleNumber); uint256 penalty; // penalty received for not taking enough risk (_commission, penalty) = commissionBalanceOf(msg.sender); // record the redemption to prevent double-redemption for ( uint256 i = lastCommissionRedemption(msg.sender); i < cycleNumber; i++ ) { _hasRedeemedCommissionForCycle[msg.sender][i] = true; } _lastCommissionRedemption[msg.sender] = cycleNumber; // record the decrease in commission pool totalCommissionLeft = totalCommissionLeft.sub(_commission); // include commission penalty to this cycle's total commission pool _totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle( cycleNumber ) .add(penalty); // clear investment arrays to save space delete userInvestments[msg.sender]; delete userCompoundOrders[msg.sender]; emit CommissionPaid(cycleNumber, msg.sender, _commission); } /** * @notice Redeems commission for a particular cycle. Updates the related variables. * @param _cycle the cycle for which the commission will be redeemed * @return the amount of commission to be redeemed */ function __redeemCommissionForCycle(uint256 _cycle) internal returns (uint256 _commission) { require(!hasRedeemedCommissionForCycle(msg.sender, _cycle)); uint256 penalty; // penalty received for not taking enough risk (_commission, penalty) = commissionOfAt(msg.sender, _cycle); _hasRedeemedCommissionForCycle[msg.sender][_cycle] = true; // record the decrease in commission pool totalCommissionLeft = totalCommissionLeft.sub(_commission); // include commission penalty to this cycle's total commission pool _totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle( cycleNumber ) .add(penalty); // clear investment arrays to save space delete userInvestments[msg.sender]; delete userCompoundOrders[msg.sender]; emit CommissionPaid(_cycle, msg.sender, _commission); } /** * @notice Handles deposits by minting PeakDeFi Shares & updating total funds. * @param _depositUSDCAmount The amount of the deposit in USDC */ function __deposit(uint256 _depositUSDCAmount) internal { // Register investment and give shares if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) { require(sToken.generateTokens(msg.sender, _depositUSDCAmount)); } else { require( sToken.generateTokens( msg.sender, _depositUSDCAmount.mul(sToken.totalSupply()).div( totalFundsInUSDC ) ) ); } totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount); } /** PeakDeFi */ /** * @notice Returns the commission balance of `_referrer` * @return the commission balance, denoted in USDC */ function peakReferralCommissionBalanceOf(address _referrer) public view returns (uint256 _commission) { if (peakReferralLastCommissionRedemption(_referrer) >= cycleNumber) { return (0); } uint256 cycle = peakReferralLastCommissionRedemption(_referrer) > 0 ? peakReferralLastCommissionRedemption(_referrer) : 1; uint256 cycleCommission; for (; cycle < cycleNumber; cycle++) { (cycleCommission) = peakReferralCommissionOfAt(_referrer, cycle); _commission = _commission.add(cycleCommission); } } /** * @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle * @return the commission amount, denoted in USDC */ function peakReferralCommissionOfAt(address _referrer, uint256 _cycle) public view returns (uint256 _commission) { _commission = peakReferralTotalCommissionOfCycle(_cycle) .mul( peakReferralToken.balanceOfAt( _referrer, managePhaseEndBlock(_cycle) ) ) .div(peakReferralToken.totalSupplyAt(managePhaseEndBlock(_cycle))); } /** * @notice Redeems commission. */ function peakReferralRedeemCommission() public during(CyclePhase.Intermission) nonReentrant { uint256 commission = __peakReferralRedeemCommission(); // Transfer the commission in USDC usdc.safeApprove(address(peakReward), commission); peakReward.payCommission(msg.sender, address(usdc), commission, false); } /** * @notice Redeems commission for a particular cycle. * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function peakReferralRedeemCommissionForCycle(uint256 _cycle) public during(CyclePhase.Intermission) nonReentrant { require(_cycle < cycleNumber); uint256 commission = __peakReferralRedeemCommissionForCycle(_cycle); // Transfer the commission in USDC usdc.safeApprove(address(peakReward), commission); peakReward.payCommission(msg.sender, address(usdc), commission, false); } /** * @notice Redeems the commission for all previous cycles. Updates the related variables. * @return the amount of commission to be redeemed */ function __peakReferralRedeemCommission() internal returns (uint256 _commission) { require(peakReferralLastCommissionRedemption(msg.sender) < cycleNumber); _commission = peakReferralCommissionBalanceOf(msg.sender); // record the redemption to prevent double-redemption for ( uint256 i = peakReferralLastCommissionRedemption(msg.sender); i < cycleNumber; i++ ) { _peakReferralHasRedeemedCommissionForCycle[msg.sender][i] = true; } _peakReferralLastCommissionRedemption[msg.sender] = cycleNumber; // record the decrease in commission pool peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub( _commission ); emit PeakReferralCommissionPaid(cycleNumber, msg.sender, _commission); } /** * @notice Redeems commission for a particular cycle. Updates the related variables. * @param _cycle the cycle for which the commission will be redeemed * @return the amount of commission to be redeemed */ function __peakReferralRedeemCommissionForCycle(uint256 _cycle) internal returns (uint256 _commission) { require(!peakReferralHasRedeemedCommissionForCycle(msg.sender, _cycle)); _commission = peakReferralCommissionOfAt(msg.sender, _cycle); _peakReferralHasRedeemedCommissionForCycle[msg.sender][_cycle] = true; // record the decrease in commission pool peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub( _commission ); emit PeakReferralCommissionPaid(_cycle, msg.sender, _commission); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "../interfaces/CERC20.sol"; import "../interfaces/Comptroller.sol"; contract TestCERC20 is CERC20 { using SafeMath for uint; uint public constant PRECISION = 10 ** 18; uint public constant MAX_UINT = 2 ** 256 - 1; address public _underlying; uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION; mapping(address => uint) public _balanceOf; mapping(address => uint) public _borrowBalanceCurrent; Comptroller public COMPTROLLER; constructor(address __underlying, address _comptrollerAddr) public { _underlying = __underlying; COMPTROLLER = Comptroller(_comptrollerAddr); } function mint(uint mintAmount) external returns (uint) { ERC20Detailed token = ERC20Detailed(_underlying); require(token.transferFrom(msg.sender, address(this), mintAmount)); _balanceOf[msg.sender] = _balanceOf[msg.sender].add(mintAmount.mul(10 ** this.decimals()).div(PRECISION)); return 0; } function redeemUnderlying(uint redeemAmount) external returns (uint) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION)); ERC20Detailed token = ERC20Detailed(_underlying); require(token.transfer(msg.sender, redeemAmount)); return 0; } function borrow(uint amount) external returns (uint) { // add to borrow balance _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount); // transfer asset ERC20Detailed token = ERC20Detailed(_underlying); require(token.transfer(msg.sender, amount)); return 0; } function repayBorrow(uint amount) external returns (uint) { // accept repayment ERC20Detailed token = ERC20Detailed(_underlying); uint256 repayAmount = amount == MAX_UINT ? _borrowBalanceCurrent[msg.sender] : amount; require(token.transferFrom(msg.sender, address(this), repayAmount)); // subtract from borrow balance _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(repayAmount); return 0; } function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; } function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; } function underlying() external view returns (address) { return _underlying; } function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; } function decimals() external view returns (uint) { return 8; } } pragma solidity 0.5.17; import "./TestCERC20.sol"; contract TestCERC20Factory { mapping(address => address) public createdTokens; event CreatedToken(address underlying, address cToken); function newToken(address underlying, address comptroller) public returns(address) { require(createdTokens[underlying] == address(0)); TestCERC20 token = new TestCERC20(underlying, comptroller); createdTokens[underlying] = address(token); emit CreatedToken(underlying, address(token)); return address(token); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/CEther.sol"; import "../interfaces/Comptroller.sol"; contract TestCEther is CEther { using SafeMath for uint; uint public constant PRECISION = 10 ** 18; uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION; mapping(address => uint) public _balanceOf; mapping(address => uint) public _borrowBalanceCurrent; Comptroller public COMPTROLLER; constructor(address _comptrollerAddr) public { COMPTROLLER = Comptroller(_comptrollerAddr); } function mint() external payable { _balanceOf[msg.sender] = _balanceOf[msg.sender].add(msg.value.mul(10 ** this.decimals()).div(PRECISION)); } function redeemUnderlying(uint redeemAmount) external returns (uint) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION)); msg.sender.transfer(redeemAmount); return 0; } function borrow(uint amount) external returns (uint) { // add to borrow balance _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount); // transfer asset msg.sender.transfer(amount); return 0; } function repayBorrow() external payable { _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(msg.value); } function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; } function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; } function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; } function decimals() external view returns (uint) { return 8; } function() external payable {} } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/Comptroller.sol"; import "../interfaces/PriceOracle.sol"; import "../interfaces/CERC20.sol"; contract TestComptroller is Comptroller { using SafeMath for uint; uint256 internal constant PRECISION = 10 ** 18; mapping(address => address[]) public getAssetsIn; uint256 internal collateralFactor = 2 * PRECISION / 3; constructor() public {} function enterMarkets(address[] calldata cTokens) external returns (uint[] memory) { uint[] memory errors = new uint[](cTokens.length); for (uint256 i = 0; i < cTokens.length; i = i.add(1)) { getAssetsIn[msg.sender].push(cTokens[i]); errors[i] = 0; } return errors; } function markets(address /*cToken*/) external view returns (bool isListed, uint256 collateralFactorMantissa) { return (true, collateralFactor); } } pragma solidity 0.5.17; import "../interfaces/KyberNetwork.sol"; import "../Utils.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; contract TestKyberNetwork is KyberNetwork, Utils(address(0), address(0), address(0)), Ownable { mapping(address => uint256) public priceInUSDC; constructor(address[] memory _tokens, uint256[] memory _pricesInUSDC) public { for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { priceInUSDC[_tokens[i]] = _pricesInUSDC[i]; } } function setTokenPrice(address _token, uint256 _priceInUSDC) public onlyOwner { priceInUSDC[_token] = _priceInUSDC; } function setAllTokenPrices(address[] memory _tokens, uint256[] memory _pricesInUSDC) public onlyOwner { for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { priceInUSDC[_tokens[i]] = _pricesInUSDC[i]; } } function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint /*srcQty*/) external view returns (uint expectedRate, uint slippageRate) { uint256 result = priceInUSDC[address(src)].mul(10**getDecimals(dest)).mul(PRECISION).div(priceInUSDC[address(dest)].mul(10**getDecimals(src))); return (result, result); } function tradeWithHint( ERC20Detailed src, uint srcAmount, ERC20Detailed dest, address payable destAddress, uint maxDestAmount, uint /*minConversionRate*/, address /*walletId*/, bytes calldata /*hint*/ ) external payable returns(uint) { require(calcDestAmount(src, srcAmount, dest) <= maxDestAmount); if (address(src) == address(ETH_TOKEN_ADDRESS)) { require(srcAmount == msg.value); } else { require(src.transferFrom(msg.sender, address(this), srcAmount)); } if (address(dest) == address(ETH_TOKEN_ADDRESS)) { destAddress.transfer(calcDestAmount(src, srcAmount, dest)); } else { require(dest.transfer(destAddress, calcDestAmount(src, srcAmount, dest))); } return calcDestAmount(src, srcAmount, dest); } function calcDestAmount( ERC20Detailed src, uint srcAmount, ERC20Detailed dest ) internal view returns (uint destAmount) { return srcAmount.mul(priceInUSDC[address(src)]).mul(10**getDecimals(dest)).div(priceInUSDC[address(dest)].mul(10**getDecimals(src))); } function() external payable {} } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "../interfaces/PriceOracle.sol"; import "../interfaces/CERC20.sol"; contract TestPriceOracle is PriceOracle, Ownable { using SafeMath for uint; uint public constant PRECISION = 10 ** 18; address public CETH_ADDR; mapping(address => uint256) public priceInUSD; constructor(address[] memory _tokens, uint256[] memory _pricesInUSD, address _cETH) public { for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { priceInUSD[_tokens[i]] = _pricesInUSD[i]; } CETH_ADDR = _cETH; } function setTokenPrice(address _token, uint256 _priceInUSD) public onlyOwner { priceInUSD[_token] = _priceInUSD; } function getUnderlyingPrice(address _cToken) external view returns (uint) { if (_cToken == CETH_ADDR) { return priceInUSD[_cToken]; } CERC20 cToken = CERC20(_cToken); ERC20Detailed underlying = ERC20Detailed(cToken.underlying()); return priceInUSD[_cToken].mul(PRECISION).div(10 ** uint256(underlying.decimals())); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; /** * @title An ERC20 token used for testing. * @author Zefram Lou (Zebang Liu) */ contract TestToken is ERC20Mintable, ERC20Burnable, ERC20Detailed { constructor(string memory name, string memory symbol, uint8 decimals) public ERC20Detailed(name, symbol, decimals) {} } pragma solidity 0.5.17; import "./TestToken.sol"; contract TestTokenFactory { mapping(bytes32 => address) public createdTokens; event CreatedToken(string symbol, address addr); function newToken(string memory name, string memory symbol, uint8 decimals) public returns(address) { bytes32 symbolHash = keccak256(abi.encodePacked(symbol)); require(createdTokens[symbolHash] == address(0)); TestToken token = new TestToken(name, symbol, decimals); token.addMinter(msg.sender); token.renounceMinter(); createdTokens[symbolHash] = address(token); emit CreatedToken(symbol, address(token)); return address(token); } function getToken(string memory symbol) public view returns(address) { return createdTokens[keccak256(abi.encodePacked(symbol))]; } } pragma solidity 0.5.17; contract TestUniswapOracle { function update() external returns (bool success) { return true; } function consult(address token, uint256 amountIn) external view returns (uint256 amountOut) { return 3 * 10**5; // 1 PEAK = 0.30 USDC } }
Redeems commission./ Deposit commission into fund Emit deposit event Transfer the commission in USDC
function redeemCommission(bool _inShares) public during(CyclePhase.Intermission) nonReentrant { uint256 commission = __redeemCommission(); if (_inShares) { __deposit(commission); emit Deposit( cycleNumber, msg.sender, USDC_ADDR, commission, commission, now ); usdc.safeTransfer(msg.sender, commission); } }
15,852,123
// SPDX-License-Identifier: UNLICENSED // Cauldron // ( ( ( // )\ ) ( )\ )\ ) ( // (((_) ( /( ))\ ((_)(()/( )( ( ( // )\___ )(_)) /((_) _ ((_))(()\ )\ )\ ) // ((/ __|((_)_ (_))( | | _| | ((_) ((_) _(_/( // | (__ / _` || || || |/ _` | | '_|/ _ \| ' \)) // \___|\__,_| \_,_||_|\__,_| |_| \___/|_||_| // Copyright (c) 2021 BoringCrypto - All rights reserved // Twitter: @Boring_Crypto // Special thanks to: // @0xKeno - for all his invaluable contributions // @burger_crypto - for the idea of trying to let the LPs benefit from liquidations pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol"; import "@boringcrypto/boring-solidity/contracts/ERC20.sol"; import "@boringcrypto/boring-solidity/contracts/interfaces/IMasterContract.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringRebase.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "./MagicInternetMoney.sol"; import "./interfaces/IOracle.sol"; import "./interfaces/ISwapper.sol"; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly /// @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. contract CauldronV3 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); event LogInterestChange(uint64 oldInterestRate, uint64 newInterestRate); event LogChangeBorrowLimit(uint128 newLimit, uint128 perAddressPart); event LogLiquidation( address indexed from, address indexed user, address indexed to, uint256 collateralShare, uint256 borrowAmount, uint256 borrowPart ); // Immutables (for MasterContract and all clones) IBentoBoxV1 public immutable bentoBox; CauldronV3 public immutable masterContract; IERC20 public immutable magicInternetMoney; // MasterContract variables address public feeTo; // Per clone variables // Clone init settings IERC20 public collateral; IOracle public oracle; bytes public oracleData; struct BorrowCap { uint128 total; uint128 borrowPartPerAddress; } BorrowCap public borrowLimit; // Total amounts uint256 public totalCollateralShare; // Total collateral supplied Rebase public totalBorrow; // elastic = Total token amount to be repayed by borrowers, base = Total parts of the debt held by borrowers // User balances mapping(address => uint256) public userCollateralShare; mapping(address => uint256) public userBorrowPart; /// @notice Exchange and interest rate tracking. /// This is 'cached' here because calls to Oracles can be very expensive. uint256 public exchangeRate; struct AccrueInfo { uint64 lastAccrued; uint128 feesEarned; uint64 INTEREST_PER_SECOND; } AccrueInfo public accrueInfo; /// @notice tracking of last interest update uint256 private lastInterestUpdate; // Settings uint256 public COLLATERIZATION_RATE; uint256 private constant COLLATERIZATION_RATE_PRECISION = 1e5; // Must be less than EXCHANGE_RATE_PRECISION (due to optimization in math) 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; modifier onlyMasterContractOwner() { require(msg.sender == masterContract.owner(), "Caller is not the owner"); _; } /// @notice The constructor is only used for the initial master contract. Subsequent clones are initialised via `init`. constructor(IBentoBoxV1 bentoBox_, IERC20 magicInternetMoney_) public { bentoBox = bentoBox_; magicInternetMoney = magicInternetMoney_; masterContract = this; } /// @notice Serves as the constructor for clones, as clones can't have a regular constructor /// @dev `data` is abi encoded in the format: (IERC20 collateral, IERC20 asset, IOracle oracle, bytes oracleData) 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)); borrowLimit = BorrowCap(type(uint128).max, type(uint128).max); require(address(collateral) != address(0), "Cauldron: bad pair"); (, exchangeRate) = oracle.get(oracleData); } /// @notice Accrues the interest on the borrowed tokens and handles the accumulation of fees. function accrue() public { AccrueInfo memory _accrueInfo = accrueInfo; // Number of seconds since accrue was called 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; } // Accrue interest uint128 extraAmount = (uint256(_totalBorrow.elastic).mul(_accrueInfo.INTEREST_PER_SECOND).mul(elapsedTime) / 1e18).to128(); _totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount); _accrueInfo.feesEarned = _accrueInfo.feesEarned.add(extraAmount); totalBorrow = _totalBorrow; accrueInfo = _accrueInfo; emit LogAccrue(extraAmount); } /// @notice Concrete implementation of `isSolvent`. Includes a third parameter to allow caching `exchangeRate`. /// @param _exchangeRate The exchange rate. Used to cache the `exchangeRate` between calls. function _isSolvent(address user, uint256 _exchangeRate) internal view returns (bool) { // accrue must have already been called! 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 ) >= // Moved exchangeRate here instead of dividing the other side to preserve more precision borrowPart.mul(_totalBorrow.elastic).mul(_exchangeRate) / _totalBorrow.base; } /// @dev Checks if the user is solvent in the closed liquidation case at the end of the function body. modifier solvent() { _; (, uint256 _exchangeRate) = updateExchangeRate(); require(_isSolvent(msg.sender, _exchangeRate), "Cauldron: user insolvent"); } /// @notice Gets the exchange rate. I.e how much collateral to buy 1e18 asset. /// This function is supposed to be invoked if needed because Oracle queries can be expensive. /// @return updated True if `exchangeRate` was updated. /// @return rate The new exchange rate. function updateExchangeRate() public returns (bool updated, uint256 rate) { (updated, rate) = oracle.get(oracleData); if (updated) { exchangeRate = rate; emit LogExchangeRate(rate); } else { // Return the old rate if fetching wasn't successful rate = exchangeRate; } } /// @dev Helper function to move tokens. /// @param token The ERC-20 token. /// @param share The amount in shares to add. /// @param total Grand total amount to deduct from this contract's balance. Only applicable if `skim` is True. /// Only used for accounting checks. /// @param skim If True, only does a balance check on this contract. /// False if tokens from msg.sender in `bentoBox` should be transferred. 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"); } else { bentoBox.transfer(token, msg.sender, address(this), share); } } /// @notice Adds `collateral` from msg.sender to the account `to`. /// @param to The receiver of the tokens. /// @param skim True if the amount should be skimmed from the deposit balance of msg.sender.x /// False if tokens from msg.sender in `bentoBox` should be transferred. /// @param share The amount of shares to add for `to`. 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); } /// @dev Concrete implementation of `removeCollateral`. 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); } /// @notice Removes `share` amount of collateral and transfers it to `to`. /// @param to The receiver of the shares. /// @param share Amount of shares to remove. function removeCollateral(address to, uint256 share) public solvent { // accrue must be called because we check solvency accrue(); _removeCollateral(to, share); } /// @dev Concrete implementation of `borrow`. function _borrow(address to, uint256 amount) internal returns (uint256 part, uint256 share) { uint256 feeAmount = amount.mul(BORROW_OPENING_FEE) / BORROW_OPENING_FEE_PRECISION; // A flat % fee is charged for any borrow (totalBorrow, part) = totalBorrow.add(amount.add(feeAmount), true); BorrowCap memory cap = borrowLimit; require(totalBorrow.elastic <= cap.total, "Borrow Limit reached"); accrueInfo.feesEarned = accrueInfo.feesEarned.add(uint128(feeAmount)); uint256 newBorrowPart = userBorrowPart[msg.sender].add(part); require(newBorrowPart <= cap.borrowPartPerAddress, "Borrow Limit reached"); userBorrowPart[msg.sender] = newBorrowPart; // As long as there are tokens on this contract you can 'mint'... this enables limiting borrows share = bentoBox.toShare(magicInternetMoney, amount, false); bentoBox.transfer(magicInternetMoney, address(this), to, share); emit LogBorrow(msg.sender, to, amount.add(feeAmount), part); } /// @notice Sender borrows `amount` and transfers it to `to`. /// @return part Total part of the debt held by borrowers. /// @return share Total amount in shares borrowed. function borrow(address to, uint256 amount) public solvent returns (uint256 part, uint256 share) { accrue(); (part, share) = _borrow(to, amount); } /// @dev Concrete implementation of `repay`. 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); } /// @notice Repays a loan. /// @param to Address of the user this payment should go. /// @param skim True if the amount should be skimmed from the deposit balance of msg.sender. /// False if tokens from msg.sender in `bentoBox` should be transferred. /// @param part The amount to repay. See `userBorrowPart`. /// @return amount The total amount repayed. function repay( address to, bool skim, uint256 part ) public returns (uint256 amount) { accrue(); amount = _repay(to, skim, part); } // Functions that need accrue to be called uint8 internal constant ACTION_REPAY = 2; 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; // Functions that don't need accrue to be called uint8 internal constant ACTION_ADD_COLLATERAL = 10; uint8 internal constant ACTION_UPDATE_EXCHANGE_RATE = 11; // Function on BentoBox uint8 internal constant ACTION_BENTO_DEPOSIT = 20; 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; // Any external call (except to BentoBox) uint8 internal constant ACTION_CALL = 30; int256 internal constant USE_VALUE1 = -1; int256 internal constant USE_VALUE2 = -2; /// @dev Helper function for choosing the correct value (`value1` or `value2`) depending on `inNum`. function _num( int256 inNum, uint256 value1, uint256 value2 ) internal pure returns (uint256 outNum) { outNum = inNum >= 0 ? uint256(inNum) : (inNum == USE_VALUE1 ? value1 : value2); } /// @dev Helper function for depositing into `bentoBox`. 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)); amount = int256(_num(amount, value1, value2)); // Done this way to avoid stack too deep errors share = int256(_num(share, value1, value2)); return bentoBox.deposit{value: value}(token, msg.sender, to, uint256(amount), uint256(share)); } /// @dev Helper function to withdraw from the `bentoBox`. 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)); } /// @dev Helper function to perform a contract call and eventually extracting revert messages on failure. /// Calls to `bentoBox` are not allowed for obvious security reasons. /// This also means that calls made from this contract shall *not* be trusted. 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); } else if (!useValue1 && useValue2) { callData = abi.encodePacked(callData, value2); } else if (useValue1 && useValue2) { callData = abi.encodePacked(callData, value1, value2); } require(callee != address(bentoBox) && callee != address(this), "Cauldron: can't call"); (bool success, bytes memory returnData) = callee.call{value: value}(callData); require(success, "Cauldron: call failed"); return (returnData, returnValues); } struct CookStatus { bool needsSolvencyCheck; bool hasAccrued; } /// @notice Executes a set of actions and allows composability (contract calls) to other contracts. /// @param actions An array with a sequence of actions to execute (see ACTION_ declarations). /// @param values A one-to-one mapped array to `actions`. ETH amounts to send along with the actions. /// Only applicable to `ACTION_CALL`, `ACTION_BENTO_DEPOSIT`. /// @param datas A one-to-one mapped array to `actions`. Contains abi encoded data of function arguments. /// @return value1 May contain the first positioned return value of the last executed action (if applicable). /// @return value2 May contain the second positioned return value of the last executed action which returns 2 values (if applicable). 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)); } else if (action == ACTION_REPAY) { (int256 part, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); _repay(to, skim, _num(part, value1, value2)); } else if (action == ACTION_REMOVE_COLLATERAL) { (int256 share, address to) = abi.decode(datas[i], (int256, address)); _removeCollateral(to, _num(share, value1, value2)); status.needsSolvencyCheck = true; } else if (action == ACTION_BORROW) { (int256 amount, address to) = abi.decode(datas[i], (int256, address)); (value1, value2) = _borrow(to, _num(amount, value1, value2)); status.needsSolvencyCheck = true; } else if (action == ACTION_UPDATE_EXCHANGE_RATE) { (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"); } else if (action == ACTION_BENTO_SETAPPROVAL) { (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); } else if (action == ACTION_BENTO_DEPOSIT) { (value1, value2) = _bentoDeposit(datas[i], values[i], value1, value2); } else if (action == ACTION_BENTO_WITHDRAW) { (value1, value2) = _bentoWithdraw(datas[i], value1, value2); } else if (action == ACTION_BENTO_TRANSFER) { (IERC20 token, address to, int256 share) = abi.decode(datas[i], (IERC20, address, int256)); bentoBox.transfer(token, msg.sender, to, _num(share, value1, value2)); } else if (action == ACTION_BENTO_TRANSFER_MULTIPLE) { (IERC20 token, address[] memory tos, uint256[] memory shares) = abi.decode(datas[i], (IERC20, address[], uint256[])); bentoBox.transferMultiple(token, msg.sender, tos, shares); } else if (action == ACTION_CALL) { (bytes memory returnData, uint8 returnValues) = _call(values[i], datas[i], value1, value2); if (returnValues == 1) { (value1) = abi.decode(returnData, (uint256)); } else if (returnValues == 2) { (value1, value2) = abi.decode(returnData, (uint256, uint256)); } } else if (action == ACTION_GET_REPAY_SHARE) { int256 part = abi.decode(datas[i], (int256)); value1 = bentoBox.toShare(magicInternetMoney, totalBorrow.toElastic(_num(part, value1, value2), true), true); } else if (action == ACTION_GET_REPAY_PART) { int256 amount = abi.decode(datas[i], (int256)); value1 = totalBorrow.toBase(_num(amount, value1, value2), false); } } if (status.needsSolvencyCheck) { (, uint256 _exchangeRate) = updateExchangeRate(); require(_isSolvent(msg.sender, _exchangeRate), "Cauldron: user insolvent"); } } /// @notice Handles the liquidation of users' balances, once the users' amount of collateral is too low. /// @param users An array of user addresses. /// @param maxBorrowParts A one-to-one mapping to `users`, contains maximum (partial) borrow amounts (to liquidate) of the respective user. /// @param to Address of the receiver in open liquidations if `swapper` is zero. function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper ) public { // Oracle can fail but we still need to allow liquidations (, 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); emit LogLiquidation(msg.sender, user, to, collateralShare, borrowAmount, borrowPart); // Keep totals allCollateralShare = allCollateralShare.add(collateralShare); 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); // Apply a percentual fee share to sSpell holders { uint256 distributionAmount = (allBorrowAmount.mul(LIQUIDATION_MULTIPLIER) / LIQUIDATION_MULTIPLIER_PRECISION).sub(allBorrowAmount).mul(DISTRIBUTION_PART) / DISTRIBUTION_PRECISION; // Distribution Amount allBorrowAmount = allBorrowAmount.add(distributionAmount); accrueInfo.feesEarned = accrueInfo.feesEarned.add(distributionAmount.to128()); } uint256 allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true); // Swap using a swapper freely chosen by the caller // Open (flash) liquidation: get proceeds first and provide the borrow after bentoBox.transfer(collateral, address(this), to, allCollateralShare); if (swapper != ISwapper(0)) { swapper.swap(collateral, magicInternetMoney, msg.sender, allBorrowShare, allCollateralShare); } allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true); bentoBox.transfer(magicInternetMoney, msg.sender, address(this), allBorrowShare); } /// @notice Withdraws the fees accumulated. 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); } /// @notice Sets the beneficiary of interest accrued. /// MasterContract Only Admin function. /// @param newFeeTo The address of the receiver. function setFeeTo(address newFeeTo) public onlyOwner { feeTo = newFeeTo; emit LogFeeTo(newFeeTo); } /// @notice reduces the supply of MIM /// @param amount amount to reduce supply by function reduceSupply(uint256 amount) public onlyMasterContractOwner { bentoBox.withdraw(magicInternetMoney, address(this), masterContract.owner(), amount, 0); } /// @notice allows to change the interest rate /// @param newInterestRate new interest rate function changeInterestRate(uint64 newInterestRate) public onlyMasterContractOwner { uint64 oldInterestRate = accrueInfo.INTEREST_PER_SECOND; require(newInterestRate < oldInterestRate + oldInterestRate * 3 / 4 , "Interest rate increase > 75%"); require(lastInterestUpdate + 3 days < block.timestamp, "Update only every 3 days"); lastInterestUpdate = block.timestamp; accrueInfo.INTEREST_PER_SECOND = newInterestRate; emit LogInterestChange(oldInterestRate, newInterestRate); } /// @notice allows to change the borrow limit /// @param newBorrowLimit new borrow limit /// @param perAddressPart new borrow limit per address function changeBorrowLimit(uint128 newBorrowLimit, uint128 perAddressPart) public onlyMasterContractOwner { borrowLimit = BorrowCap(newBorrowLimit, perAddressPart); emit LogChangeBorrowLimit(newBorrowLimit, perAddressPart); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // Audit on 5-Jan-2021 by Keno and BoringCrypto // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol // Edited by BoringCrypto contract BoringOwnableData { address public owner; address public pendingOwner; } contract BoringOwnable is BoringOwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice `owner` defaults to msg.sender on construction. constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./interfaces/IERC20.sol"; import "./Domain.sol"; // solhint-disable no-inline-assembly // solhint-disable not-rely-on-time // Data part taken out for building of contracts that receive delegate calls contract ERC20Data { /// @notice owner > balance mapping. mapping(address => uint256) public balanceOf; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; } abstract contract ERC20 is IERC20, Domain { /// @notice owner > balance mapping. mapping(address => uint256) public override balanceOf; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public override allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /// @notice Transfers `amount` tokens from `msg.sender` to `to`. /// @param to The address to move the tokens. /// @param amount of the tokens to move. /// @return (bool) Returns True if succeeded. function transfer(address to, uint256 amount) public returns (bool) { // If `amount` is 0, or `msg.sender` is `to` nothing happens if (amount != 0 || msg.sender == to) { uint256 srcBalance = balanceOf[msg.sender]; require(srcBalance >= amount, "ERC20: balance too low"); if (msg.sender != to) { require(to != address(0), "ERC20: no zero address"); // Moved down so low balance calls safe some gas balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; } } emit Transfer(msg.sender, to, amount); return true; } /// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`. /// @param from Address to draw tokens from. /// @param to The address to move the tokens. /// @param amount The token amount to move. /// @return (bool) Returns True if succeeded. function transferFrom( address from, address to, uint256 amount ) public returns (bool) { // If `amount` is 0, or `from` is `to` nothing happens if (amount != 0) { uint256 srcBalance = balanceOf[from]; require(srcBalance >= amount, "ERC20: balance too low"); if (from != to) { uint256 spenderAllowance = allowance[from][msg.sender]; // If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20). if (spenderAllowance != type(uint256).max) { require(spenderAllowance >= amount, "ERC20: allowance too low"); allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked } require(to != address(0), "ERC20: no zero address"); // Moved down so other failed calls safe some gas balanceOf[from] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; } } emit Transfer(from, to, amount); return true; } /// @notice Approves `amount` from sender to be spend by `spender`. /// @param spender Address of the party that can draw from msg.sender's account. /// @param amount The maximum collective amount that `spender` can draw. /// @return (bool) Returns True if approved. function approve(address spender, uint256 amount) public override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32) { return _domainSeparator(); } // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @notice Approves `value` from `owner_` to be spend by `spender`. /// @param owner_ Address of the owner. /// @param spender The address of the spender that gets approved to draw from `owner_`. /// @param value The maximum collective amount that `spender` can draw. /// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds). function permit( address owner_, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(owner_ != address(0), "ERC20: Owner cannot be 0"); require(block.timestamp < deadline, "ERC20: Expired"); require( ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) == owner_, "ERC20: Invalid Signature" ); allowance[owner_][spender] = value; emit Approval(owner_, spender, value); } } contract ERC20WithSupply is IERC20, ERC20 { uint256 public override totalSupply; function _mint(address user, uint256 amount) private { uint256 newTotalSupply = totalSupply + amount; require(newTotalSupply >= totalSupply, "Mint overflow"); totalSupply = newTotalSupply; balanceOf[user] += amount; } function _burn(address user, uint256 amount) private { require(balanceOf[user] >= amount, "Burn too much"); totalSupply -= amount; balanceOf[user] -= amount; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IMasterContract { /// @notice Init function that gets called from `BoringFactory.deploy`. /// Also kown as the constructor for cloned contracts. /// Any ETH send to `BoringFactory.deploy` ends up here. /// @param data Can be abi encoded arguments or anything else. function init(bytes calldata data) external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./BoringMath.sol"; struct Rebase { uint128 elastic; uint128 base; } /// @notice A rebasing library using overflow-/underflow-safe math. library RebaseLibrary { using BoringMath for uint256; using BoringMath128 for uint128; /// @notice Calculates the base value in relationship to `elastic` and `total`. function toBase( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (uint256 base) { if (total.elastic == 0) { base = elastic; } else { base = elastic.mul(total.base) / total.elastic; if (roundUp && base.mul(total.elastic) / total.base < elastic) { base = base.add(1); } } } /// @notice Calculates the elastic value in relationship to `base` and `total`. function toElastic( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (uint256 elastic) { if (total.base == 0) { elastic = base; } else { elastic = base.mul(total.elastic) / total.base; if (roundUp && elastic.mul(total.base) / total.elastic < base) { elastic = elastic.add(1); } } } /// @notice Add `elastic` to `total` and doubles `total.base`. /// @return (Rebase) The new total. /// @return base in relationship to `elastic`. function add( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (Rebase memory, uint256 base) { base = toBase(total, elastic, roundUp); total.elastic = total.elastic.add(elastic.to128()); total.base = total.base.add(base.to128()); return (total, base); } /// @notice Sub `base` from `total` and update `total.elastic`. /// @return (Rebase) The new total. /// @return elastic in relationship to `base`. function sub( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (Rebase memory, uint256 elastic) { elastic = toElastic(total, base, roundUp); total.elastic = total.elastic.sub(elastic.to128()); total.base = total.base.sub(base.to128()); return (total, elastic); } /// @notice Add `elastic` and `base` to `total`. function add( Rebase memory total, uint256 elastic, uint256 base ) internal pure returns (Rebase memory) { total.elastic = total.elastic.add(elastic.to128()); total.base = total.base.add(base.to128()); return total; } /// @notice Subtract `elastic` and `base` to `total`. function sub( Rebase memory total, uint256 elastic, uint256 base ) internal pure returns (Rebase memory) { total.elastic = total.elastic.sub(elastic.to128()); total.base = total.base.sub(base.to128()); return total; } /// @notice Add `elastic` to `total` and update storage. /// @return newElastic Returns updated `elastic`. function addElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) { newElastic = total.elastic = total.elastic.add(elastic.to128()); } /// @notice Subtract `elastic` from `total` and update storage. /// @return newElastic Returns updated `elastic`. function subElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) { newElastic = total.elastic = total.elastic.sub(elastic.to128()); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../interfaces/IERC20.sol"; // solhint-disable avoid-low-level-calls library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) function returnDataToString(bytes memory data) internal pure returns (string memory) { if (data.length >= 64) { return abi.decode(data, (string)); } else if (data.length == 32) { uint8 i = 0; while(i < 32 && data[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && data[i] != 0; i++) { bytesArray[i] = data[i]; } return string(bytesArray); } else { return "???"; } } /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import '@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol'; import '@boringcrypto/boring-solidity/contracts/libraries/BoringRebase.sol'; import './IBatchFlashBorrower.sol'; import './IFlashBorrower.sol'; import './IStrategy.sol'; interface IBentoBoxV1 { event LogDeploy(address indexed masterContract, bytes data, address indexed cloneAddress); event LogDeposit(address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share); event LogFlashLoan(address indexed borrower, address indexed token, uint256 amount, uint256 feeAmount, address indexed receiver); event LogRegisterProtocol(address indexed protocol); event LogSetMasterContractApproval(address indexed masterContract, address indexed user, bool approved); event LogStrategyDivest(address indexed token, uint256 amount); event LogStrategyInvest(address indexed token, uint256 amount); event LogStrategyLoss(address indexed token, uint256 amount); event LogStrategyProfit(address indexed token, uint256 amount); event LogStrategyQueued(address indexed token, address indexed strategy); event LogStrategySet(address indexed token, address indexed strategy); event LogStrategyTargetPercentage(address indexed token, uint256 targetPercentage); event LogTransfer(address indexed token, address indexed from, address indexed to, uint256 share); event LogWhiteListMasterContract(address indexed masterContract, bool approved); event LogWithdraw(address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function balanceOf(IERC20, address) external view returns (uint256); function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results); function batchFlashLoan(IBatchFlashBorrower borrower, address[] calldata receivers, IERC20[] calldata tokens, uint256[] calldata amounts, bytes calldata data) external; function claimOwnership() external; function deploy(address masterContract, bytes calldata data, bool useCreate2) external payable; function deposit(IERC20 token_, address from, address to, uint256 amount, uint256 share) external payable returns (uint256 amountOut, uint256 shareOut); function flashLoan(IFlashBorrower borrower, address receiver, IERC20 token, uint256 amount, bytes calldata data) external; function harvest(IERC20 token, bool balance, uint256 maxChangeAmount) external; function masterContractApproved(address, address) external view returns (bool); function masterContractOf(address) external view returns (address); function nonces(address) external view returns (uint256); function owner() external view returns (address); function pendingOwner() external view returns (address); function pendingStrategy(IERC20) external view returns (IStrategy); function permitToken(IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function registerProtocol() external; function setMasterContractApproval(address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) external; function setStrategy(IERC20 token, IStrategy newStrategy) external; function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_) external; function strategy(IERC20) external view returns (IStrategy); function strategyData(IERC20) external view returns (uint64 strategyStartDate, uint64 targetPercentage, uint128 balance); function toAmount(IERC20 token, uint256 share, bool roundUp) external view returns (uint256 amount); function toShare(IERC20 token, uint256 amount, bool roundUp) external view returns (uint256 share); function totals(IERC20) external view returns (Rebase memory totals_); function transfer(IERC20 token, address from, address to, uint256 share) external; function transferMultiple(IERC20 token, address from, address[] calldata tos, uint256[] calldata shares) external; function transferOwnership(address newOwner, bool direct, bool renounce) external; function whitelistMasterContract(address masterContract, bool approved) external; function whitelistedMasterContracts(address) external view returns (bool); function withdraw(IERC20 token_, address from, address to, uint256 amount, uint256 share) external returns (uint256 amountOut, uint256 shareOut); } // SPDX-License-Identifier: MIT // Magic Internet Money // ███╗ ███╗██╗███╗ ███╗ // ████╗ ████║██║████╗ ████║ // ██╔████╔██║██║██╔████╔██║ // ██║╚██╔╝██║██║██║╚██╔╝██║ // ██║ ╚═╝ ██║██║██║ ╚═╝ ██║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═╝ // BoringCrypto, 0xMerlin pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/ERC20.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.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. contract MagicInternetMoney is ERC20, BoringOwnable { using BoringMath for uint256; // ERC20 'variables' string public constant symbol = "MIM"; string public constant name = "Magic Internet Money"; uint8 public constant decimals = 18; uint256 public override totalSupply; struct Minting { uint128 time; uint128 amount; } Minting public lastMint; uint256 private constant MINTING_PERIOD = 24 hours; uint256 private constant MINTING_INCREASE = 15000; uint256 private constant MINTING_PRECISION = 1e5; function mint(address to, uint256 amount) public onlyOwner { require(to != address(0), "MIM: no mint to zero address"); // Limits the amount minted per period to a convergence function, with the period duration restarting on every mint uint256 totalMintedAmount = uint256(lastMint.time < block.timestamp - MINTING_PERIOD ? 0 : lastMint.amount).add(amount); require(totalSupply == 0 || totalSupply.mul(MINTING_INCREASE) / MINTING_PRECISION >= totalMintedAmount); lastMint.time = block.timestamp.to128(); lastMint.amount = totalMintedAmount.to128(); totalSupply = totalSupply + amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } function mintToBentoBox(address clone, uint256 amount, IBentoBoxV1 bentoBox) public onlyOwner { mint(address(bentoBox), amount); bentoBox.deposit(IERC20(address(this)), address(bentoBox), clone, amount, 0); } function burn(uint256 amount) public { require(amount <= balanceOf[msg.sender], "MIM: not enough"); balanceOf[msg.sender] -= amount; totalSupply -= amount; emit Transfer(msg.sender, address(0), amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; interface IOracle { /// @notice Get the latest exchange rate. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function get(bytes calldata data) external returns (bool success, uint256 rate); /// @notice Check the last exchange rate without any state changes. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function peek(bytes calldata data) external view returns (bool success, uint256 rate); /// @notice Check the current spot exchange rate without any state changes. For oracles like TWAP this will be different from peek(). /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return rate The rate of the requested asset / pair / pool. function peekSpot(bytes calldata data) external view returns (uint256 rate); /// @notice Returns a human readable (short) name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable symbol name about this oracle. function symbol(bytes calldata data) external view returns (string memory); /// @notice Returns a human readable name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable name about this oracle. function name(bytes calldata data) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol"; interface ISwapper { /// @notice Withdraws 'amountFrom' of token 'from' from the BentoBox account for this swapper. /// Swaps it for at least 'amountToMin' of token 'to'. /// Transfers the swapped tokens of 'to' into the BentoBox using a plain ERC20 transfer. /// Returns the amount of tokens 'to' transferred to BentoBox. /// (The BentoBox skim function will be used by the caller to get the swapped funds). function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) external returns (uint256 extraShare, uint256 shareReturned); /// @notice Calculates the amount of token 'from' needed to complete the swap (amountFrom), /// this should be less than or equal to amountFromMax. /// Withdraws 'amountFrom' of token 'from' from the BentoBox account for this swapper. /// Swaps it for exactly 'exactAmountTo' of token 'to'. /// Transfers the swapped tokens of 'to' into the BentoBox using a plain ERC20 transfer. /// Transfers allocated, but unused 'from' tokens within the BentoBox to 'refundTo' (amountFromMax - amountFrom). /// Returns the amount of 'from' tokens withdrawn from BentoBox (amountFrom). /// (The BentoBox skim function will be used by the caller to get the swapped funds). function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) external returns (uint256 shareUsed, uint256 shareReturned); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, 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); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT // Based on code and smartness by Ross Campbell and Keno // Uses immutable to store the domain separator to reduce gas usage // If the chain id changes due to a fork, the forked chain will calculate on the fly. pragma solidity 0.6.12; // solhint-disable no-inline-assembly contract Domain { bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)"); // See https://eips.ethereum.org/EIPS/eip-191 string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01"; // solhint-disable var-name-mixedcase bytes32 private immutable _DOMAIN_SEPARATOR; uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID; /// @dev Calculate the DOMAIN_SEPARATOR function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) { return keccak256( abi.encode( DOMAIN_SEPARATOR_SIGNATURE_HASH, chainId, address(this) ) ); } constructor() public { uint256 chainId; assembly {chainId := chainid()} _DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = chainId); } /// @dev Return the DOMAIN_SEPARATOR // It's named internal to allow making it public from the contract that uses it by creating a simple view function // with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator. // solhint-disable-next-line func-name-mixedcase function _domainSeparator() internal view returns (bytes32) { uint256 chainId; assembly {chainId := chainid()} return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); } function _getDigest(bytes32 dataHash) internal view returns (bytes32 digest) { digest = keccak256( abi.encodePacked( EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, _domainSeparator(), dataHash ) ); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import '@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol'; interface IBatchFlashBorrower { function onBatchFlashLoan( address sender, IERC20[] calldata tokens, uint256[] calldata amounts, uint256[] calldata fees, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import '@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol'; interface IFlashBorrower { function onFlashLoan( address sender, IERC20 token, uint256 amount, uint256 fee, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IStrategy { // Send the assets to the Strategy and call skim to invest them function skim(uint256 amount) external; // Harvest any profits made converted to the asset and pass them to the caller function harvest(uint256 balance, address sender) external returns (int256 amountAdded); // Withdraw assets. The returned amount can differ from the requested amount due to rounding. // The actualAmount should be very close to the amount. The difference should NOT be used to report a loss. That's what harvest is for. function withdraw(uint256 amount) external returns (uint256 actualAmount); // Withdraw all assets in the safest way possible. This shouldn't fail. function exit(uint256 balance) external returns (int256 amountAdded); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; contract SushiSwapSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public immutable bentoBox; IUniswapV2Factory public immutable factory; bytes32 public immutable pairCodeHash; constructor( IBentoBoxV1 bentoBox_, IUniswapV2Factory factory_, bytes32 pairCodeHash_ ) public { bentoBox = bentoBox_; factory = factory_; pairCodeHash = pairCodeHash_; } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (IERC20 token0, IERC20 token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); IUniswapV2Pair pair = IUniswapV2Pair( uint256( keccak256(abi.encodePacked(hex"ff", factory, keccak256(abi.encodePacked(address(token0), address(token1))), pairCodeHash)) ) ); (uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(pair), 0, shareFrom); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountTo; if (toToken > fromToken) { amountTo = getAmountOut(amountFrom, reserve0, reserve1); pair.swap(0, amountTo, address(bentoBox), new bytes(0)); } else { amountTo = getAmountOut(amountFrom, reserve1, reserve0); pair.swap(amountTo, 0, address(bentoBox), new bytes(0)); } (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { IUniswapV2Pair pair; { (IERC20 token0, IERC20 token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); pair = IUniswapV2Pair( uint256( keccak256( abi.encodePacked(hex"ff", factory, keccak256(abi.encodePacked(address(token0), address(token1))), pairCodeHash) ) ) ); } (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountToExact = bentoBox.toAmount(toToken, shareToExact, true); uint256 amountFrom; if (toToken > fromToken) { amountFrom = getAmountIn(amountToExact, reserve0, reserve1); (, shareUsed) = bentoBox.withdraw(fromToken, address(this), address(pair), amountFrom, 0); pair.swap(0, amountToExact, address(bentoBox), ""); } else { amountFrom = getAmountIn(amountToExact, reserve1, reserve0); (, shareUsed) = bentoBox.withdraw(fromToken, address(this), address(pair), amountFrom, 0); pair.swap(amountToExact, 0, address(bentoBox), ""); } bentoBox.deposit(toToken, address(bentoBox), recipient, 0, shareToExact); shareReturned = shareFromSupplied.sub(shareUsed); if (shareReturned > 0) { bentoBox.transfer(fromToken, address(this), refundTo, shareReturned); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } // SPDX-License-Identifier: GPL-3.0 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: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../libraries/UniswapV2Library.sol"; import "@sushiswap/core/contracts/uniswapv2/libraries/TransferHelper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; contract SushiSwapMultiSwapper { using BoringERC20 for IERC20; using BoringMath for uint256; address private immutable factory; IBentoBoxV1 private immutable bentoBox; bytes32 private immutable pairCodeHash; constructor( address _factory, IBentoBoxV1 _bentoBox, bytes32 _pairCodeHash ) public { factory = _factory; bentoBox = _bentoBox; pairCodeHash = _pairCodeHash; } function getOutputAmount( IERC20 tokenIn, IERC20 tokenOut, uint256 amountMinOut, address[] calldata path, uint256 shareIn ) external view returns (uint256 amountOut) { uint256 amountIn = bentoBox.toAmount(tokenIn, shareIn, false); uint256[] memory amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path, pairCodeHash); amountOut = amounts[amounts.length - 1]; } function swap( IERC20 tokenIn, IERC20 tokenOut, uint256 amountMinOut, address[] calldata path, uint256 shareIn ) external returns (uint256 amountOut, uint256 shareOut) { (uint256 amountIn, ) = bentoBox.withdraw(tokenIn, address(this), address(this), 0, shareIn); amountOut = _swapExactTokensForTokens(amountIn, amountMinOut, path, address(bentoBox)); (, shareOut) = bentoBox.deposit(tokenOut, address(bentoBox), msg.sender, amountOut, 0); } // Swaps an exact amount of tokens for another token through the path passed as an argument // Returns the amount of the final token function _swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] memory path, address to ) internal returns (uint256 amountOut) { uint256[] memory amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path, pairCodeHash); amountOut = amounts[amounts.length - 1]; require(amountOut >= amountOutMin, "insufficient-amount-out"); IERC20(path[0]).safeTransfer(UniswapV2Library.pairFor(factory, path[0], path[1], pairCodeHash), amountIn); _swap(amounts, path, to); } // requires the initial amount to have already been sent to the first pair function _swap( uint256[] memory amounts, address[] memory path, address _to ) internal virtual { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = UniswapV2Library.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2], pairCodeHash) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output, pairCodeHash)).swap(amount0Out, amount1Out, to, new bytes(0)); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/core/contracts/uniswapv2/libraries/SafeMath.sol"; library UniswapV2Library { using SafeMathUniswap for uint256; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB, bytes32 pairCodeHash ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash // init code hash ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB, bytes32 pairCodeHash ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB, pairCodeHash)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path, bytes32 pairCodeHash ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1], pairCodeHash); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( address factory, uint256 amountOut, address[] memory path, bytes32 pairCodeHash ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i], pairCodeHash); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathUniswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../libraries/UniswapV2Library.sol"; import "@sushiswap/core/contracts/uniswapv2/libraries/TransferHelper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol"; interface CurvePool { function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver ) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract SpellSwapper is BoringOwnable { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant SPELL = IERC20(0x090185f2135308BaD17527004364eBcC2D37e5F6); address public constant sSPELL = 0x26FA3fFFB6EfE8c1E69103aCb4044C26B9A106a9; IUniswapV2Pair constant SPELL_WETH = IUniswapV2Pair(0xb5De0C3753b6E1B4dBA616Db82767F17513E6d4E); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); address public constant treasury = 0x5A7C5505f3CFB9a0D9A8493EC41bf27EE48c406D; mapping(address => bool) public verified; constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); verified[msg.sender] = true; } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } modifier onlyVerified() { require(verified[msg.sender], "Only verified operators"); _; } function setVerified(address operator, bool status) public onlyOwner { verified[operator] = status; } // Swaps to a flexible amount, from an exact input amount function swap(uint256 amountToMin) public onlyVerified { uint256 amountFirst; uint256 amountIntermediate; { uint256 shareFrom = bentoBox.balanceOf(MIM, address(this)); uint256 treasuryShare = shareFrom / 4; bentoBox.withdraw(MIM, address(this), treasury, 0, treasuryShare); (uint256 amountMIMFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom.sub(treasuryShare)); amountFirst = MIM3POOL.exchange_underlying(0, 3, amountMIMFrom, 0, address(pair)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0); } uint256 amountThird; { pair.swap(amountIntermediate, 0, address(SPELL_WETH), new bytes(0)); (uint256 reserve0, uint256 reserve1, ) = SPELL_WETH.getReserves(); amountThird = getAmountOut(amountIntermediate, reserve1, reserve0); require(amountThird >= amountToMin, "Minimum must be reached"); } SPELL_WETH.swap(amountThird, 0, sSPELL, new bytes(0)); } } // SPDX-License-Identifier: MIT // Spell // Special thanks to: // @BoringCrypto for his great libraries pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/ERC20.sol"; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol"; /// @title Spell /// @author 0xMerlin /// @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. contract Spell is ERC20, BoringOwnable { using BoringMath for uint256; // ERC20 'variables' string public constant symbol = "SPELL"; string public constant name = "Spell Token"; uint8 public constant decimals = 18; uint256 public override totalSupply; uint256 public constant MAX_SUPPLY = 420 * 1e27; function mint(address to, uint256 amount) public onlyOwner { require(to != address(0), "SPELL: no mint to zero address"); require(MAX_SUPPLY >= totalSupply.add(amount), "SPELL: Don't go over MAX"); totalSupply = totalSupply + amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@boringcrypto/boring-solidity/contracts/Domain.sol"; import "@boringcrypto/boring-solidity/contracts/ERC20.sol"; import "@boringcrypto/boring-solidity/contracts/BoringBatchable.sol"; // Staking in sSpell inspired by Chef Nomi's SushiBar - MIT license (originally WTFPL) // modified by BoringCrypto for DictatorDAO contract sSpell is IERC20, Domain { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; string public constant symbol = "sSPELL"; string public constant name = "Staked Spell Tokens"; uint8 public constant decimals = 18; uint256 public override totalSupply; uint256 private constant LOCK_TIME = 24 hours; IERC20 public immutable token; constructor(IERC20 _token) public { token = _token; } struct User { uint128 balance; uint128 lockedUntil; } /// @notice owner > balance mapping. mapping(address => User) public users; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public override allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function balanceOf(address user) public view override returns (uint256 balance) { return users[user].balance; } function _transfer( address from, address to, uint256 shares ) internal { User memory fromUser = users[from]; require(block.timestamp >= fromUser.lockedUntil, "Locked"); if (shares != 0) { require(fromUser.balance >= shares, "Low balance"); if (from != to) { require(to != address(0), "Zero address"); // Moved down so other failed calls safe some gas User memory toUser = users[to]; users[from].balance = fromUser.balance - shares.to128(); // Underflow is checked users[to].balance = toUser.balance + shares.to128(); // Can't overflow because totalSupply would be greater than 2^128-1; } } emit Transfer(from, to, shares); } function _useAllowance(address from, uint256 shares) internal { if (msg.sender == from) { return; } uint256 spenderAllowance = allowance[from][msg.sender]; // If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20). if (spenderAllowance != type(uint256).max) { require(spenderAllowance >= shares, "Low allowance"); allowance[from][msg.sender] = spenderAllowance - shares; // Underflow is checked } } /// @notice Transfers `shares` tokens from `msg.sender` to `to`. /// @param to The address to move the tokens. /// @param shares of the tokens to move. /// @return (bool) Returns True if succeeded. function transfer(address to, uint256 shares) public returns (bool) { _transfer(msg.sender, to, shares); return true; } /// @notice Transfers `shares` tokens from `from` to `to`. Caller needs approval for `from`. /// @param from Address to draw tokens from. /// @param to The address to move the tokens. /// @param shares The token shares to move. /// @return (bool) Returns True if succeeded. function transferFrom( address from, address to, uint256 shares ) public returns (bool) { _useAllowance(from, shares); _transfer(from, to, shares); return true; } /// @notice Approves `amount` from sender to be spend by `spender`. /// @param spender Address of the party that can draw from msg.sender's account. /// @param amount The maximum collective amount that `spender` can draw. /// @return (bool) Returns True if approved. function approve(address spender, uint256 amount) public override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32) { return _domainSeparator(); } // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @notice Approves `value` from `owner_` to be spend by `spender`. /// @param owner_ Address of the owner. /// @param spender The address of the spender that gets approved to draw from `owner_`. /// @param value The maximum collective amount that `spender` can draw. /// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds). function permit( address owner_, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(owner_ != address(0), "Zero owner"); require(block.timestamp < deadline, "Expired"); require( ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) == owner_, "Invalid Sig" ); allowance[owner_][spender] = value; emit Approval(owner_, spender, value); } /// math is ok, because amount, totalSupply and shares is always 0 <= amount <= 100.000.000 * 10^18 /// theoretically you can grow the amount/share ratio, but it's not practical and useless function mint(uint256 amount) public returns (bool) { require(msg.sender != address(0), "Zero address"); User memory user = users[msg.sender]; uint256 totalTokens = token.balanceOf(address(this)); uint256 shares = totalSupply == 0 ? amount : (amount * totalSupply) / totalTokens; user.balance += shares.to128(); user.lockedUntil = (block.timestamp + LOCK_TIME).to128(); users[msg.sender] = user; totalSupply += shares; token.safeTransferFrom(msg.sender, address(this), amount); emit Transfer(address(0), msg.sender, shares); return true; } function _burn( address from, address to, uint256 shares ) internal { require(to != address(0), "Zero address"); User memory user = users[from]; require(block.timestamp >= user.lockedUntil, "Locked"); uint256 amount = (shares * token.balanceOf(address(this))) / totalSupply; users[from].balance = user.balance.sub(shares.to128()); // Must check underflow totalSupply -= shares; token.safeTransfer(to, amount); emit Transfer(from, address(0), shares); } function burn(address to, uint256 shares) public returns (bool) { _burn(msg.sender, to, shares); return true; } function burnFrom( address from, address to, uint256 shares ) public returns (bool) { _useAllowance(from, shares); _burn(from, to, shares); return true; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto import "./interfaces/IERC20.sol"; contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable { for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); if (!success && revertOnFail) { revert(_getRevertMsg(result)); } } } } contract BoringBatchable is BaseBoringBatchable { /// @notice Call wrapper that performs `ERC20.permit` on `token`. /// Lookup `IERC20.permit`. // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { token.permit(from, to, amount, deadline, v, r, s); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface YearnVault { function withdraw(uint256 maxShares, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract YVYFISwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public immutable bentoBox; CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); YearnVault public constant YFI_VAULT = YearnVault(0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IUniswapV2Pair constant YFI_WETH = IUniswapV2Pair(0x088ee5007C98a9677165D78dD2109AE4a3D04d0C); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); constructor( IBentoBoxV1 bentoBox_ ) public { bentoBox = bentoBox_; TETHER.approve(address(MIM3POOL), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { uint256 amountFirst; { bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); uint256 amountFrom = YFI_VAULT.withdraw(type(uint256).max, address(YFI_WETH)); (uint256 reserve0, uint256 reserve1, ) = YFI_WETH.getReserves(); amountFirst = getAmountOut(amountFrom, reserve0, reserve1); } YFI_WETH.swap(0, amountFirst, address(pair), new bytes(0)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1); pair.swap(0, amountIntermediate, address(this), new bytes(0)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface YearnVault { function withdraw(uint256 maxShares, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract YVWETHSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public immutable bentoBox; CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); YearnVault public constant WETH_VAULT = YearnVault(0xa258C4606Ca8206D8aA700cE2143D7db854D168c); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); constructor( IBentoBoxV1 bentoBox_ ) public { bentoBox = bentoBox_; TETHER.approve(address(MIM3POOL), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); uint256 amountFrom = WETH_VAULT.withdraw(type(uint256).max, address(pair)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountIntermediate = getAmountOut(amountFrom, reserve0, reserve1); pair.swap(0, amountIntermediate, address(this), new bytes(0)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface YearnVault { function withdraw() external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract YVUSDTSwapper is ISwapper { using BoringMath for uint256; using BoringERC20 for IERC20; // Local variables IBentoBoxV1 public immutable bentoBox; CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); YearnVault public constant TETHER_VAULT = YearnVault(0x7Da96a3891Add058AdA2E826306D812C638D87a7); constructor( IBentoBoxV1 bentoBox_ ) public { bentoBox = bentoBox_; TETHER.approve(address(MIM3POOL), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); uint256 amountFrom =TETHER_VAULT.withdraw(); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountFrom, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (1,1); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface YearnVault { function withdraw() external returns (uint256); } contract YVUSDCSwapper is ISwapper { using BoringMath for uint256; using BoringERC20 for IERC20; // Local variables IBentoBoxV1 public immutable bentoBox; CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); IERC20 public constant TETHER = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); YearnVault public constant USDC_VAULT = YearnVault(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9); IERC20 public constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); constructor( IBentoBoxV1 bentoBox_ ) public { bentoBox = bentoBox_; USDC.approve(address(MIM3POOL), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); uint256 amountFrom = USDC_VAULT.withdraw(); uint256 amountTo = MIM3POOL.exchange_underlying(2, 0, amountFrom, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (1,1); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract YVUSDTLevSwapper { using BoringMath for uint256; using BoringERC20 for IERC20; // Local variables IBentoBoxV1 public immutable bentoBox; CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); YearnVault public constant USDT_VAULT = YearnVault(0x7Da96a3891Add058AdA2E826306D812C638D87a7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); constructor( IBentoBoxV1 bentoBox_ ) public { bentoBox = bentoBox_; MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(USDT_VAULT), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this)); uint256 amountTo = USDT_VAULT.deposit(type(uint256).max, address(bentoBox)); (, shareReturned) = bentoBox.deposit(IERC20(address(USDT_VAULT)), address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } contract YVUSDCLeverageSwapper { using BoringMath for uint256; using BoringERC20 for IERC20; // Local variables IBentoBoxV1 public immutable bentoBox; CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); YearnVault public constant USDC_VAULT = YearnVault(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9); IERC20 public constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); constructor( IBentoBoxV1 bentoBox_ ) public { bentoBox = bentoBox_; MIM.approve(address(MIM3POOL), type(uint256).max); USDC.approve(address(USDC_VAULT), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); uint256 amountIntermediate = MIM3POOL.exchange_underlying(0, 2, amountFrom, 0, address(this)); uint256 amountTo = USDC_VAULT.deposit(type(uint256).max, address(bentoBox)); (, shareReturned) = bentoBox.deposit(IERC20(address(USDC_VAULT)), address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function add_liquidity(uint256[3] memory amounts, uint256 _min_mint_amount, bool _use_underlying) external returns (uint256); } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract YVIBLevSwapper { using BoringMath for uint256; using BoringERC20 for IERC20; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); CurvePool constant public IronBank = CurvePool(0x2dded6Da1BF5DBdF597C45fcFaa3194e53EcfeAF); YearnVault constant public YVIB = YearnVault(0x27b7b1ad7288079A66d12350c828D3C00A6F07d7); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant CurveToken = IERC20(0x5282a4eF67D9C33135340fB3289cc1711c13638C); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(IronBank), type(uint256).max); CurveToken.approve(address(YVIB), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); uint256 amountIntermediate = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this)); uint256[3] memory amountsAdded = [0,0, amountIntermediate]; IronBank.add_liquidity(amountsAdded, 0, true); uint256 amountTo = YVIB.deposit(type(uint256).max, address(bentoBox)); (, shareReturned) = bentoBox.deposit(IERC20(address(YVIB)), address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function add_liquidity(uint256[3] memory amounts, uint256 _min_mint_amount, bool _use_underlying) external returns (uint256); function add_liquidity(uint256[2] memory amounts, uint256 _min_mint_amount) external payable returns (uint256); } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } interface IWETH is IERC20 { function transfer(address _to, uint256 _value) external returns (bool success); function deposit() external payable; function withdraw(uint wad) external; } contract YVCrvStETHLevSwapper { using BoringMath for uint256; using BoringERC20 for IERC20; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); CurvePool constant public STETH = CurvePool(0xDC24316b9AE028F1497c275EB9192a3Ea0f67022); YearnVault constant public YVSTETH = YearnVault(0xdCD90C7f6324cfa40d7169ef80b12031770B4325); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant CurveToken = IERC20(0x06325440D014e39736583c165C2963BA99fAf14E); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); IWETH public constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(STETH), type(uint256).max); CurveToken.approve(address(YVSTETH), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } receive() external payable {} // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); uint256 amountThird; { uint256 amountSecond = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(pair)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); amountThird = getAmountOut(amountSecond, reserve1, reserve0); pair.swap(amountThird, 0, address(this), new bytes(0)); } WETH.withdraw(amountThird); uint256[2] memory amountsAdded = [amountThird,0]; STETH.add_liquidity{value: amountThird}(amountsAdded, 0); uint256 amountTo = YVSTETH.deposit(type(uint256).max, address(bentoBox)); (, shareReturned) = bentoBox.deposit(IERC20(address(YVSTETH)), address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function add_liquidity(uint256[2] memory amounts, uint256 _min_mint_amount) external; } interface IThreeCrypto is CurvePool { function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external; } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract WethLevSwapper { using BoringMath for uint256; using BoringERC20 for IERC20; // Local variables IBentoBoxV1 public constant degenBox = IBentoBoxV1(0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); IThreeCrypto constant public threecrypto = IThreeCrypto(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(threecrypto), type(uint256).max); WETH.approve(address(degenBox), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = degenBox.withdraw(MIM, address(this), address(this), 0, shareFrom); uint256 amountOne = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this)); threecrypto.exchange(0, 2, amountOne, 0); uint256 amountTo = WETH.balanceOf(address(this)); (, shareReturned) = degenBox.deposit(WETH, address(this), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function add_liquidity(uint256[2] memory amounts, uint256 _min_mint_amount) external; } interface IThreeCrypto is CurvePool { function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external; } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract WbtcLevSwapper { using BoringMath for uint256; using BoringERC20 for IERC20; // Local variables IBentoBoxV1 public constant degenBox = IBentoBoxV1(0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); IThreeCrypto constant public threecrypto = IThreeCrypto(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(threecrypto), type(uint256).max); WBTC.approve(address(degenBox), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = degenBox.withdraw(MIM, address(this), address(this), 0, shareFrom); uint256 amountOne = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this)); threecrypto.exchange(0, 1, amountOne, 0); uint256 amountTo = WBTC.balanceOf(address(this)); (, shareReturned) = degenBox.deposit(WBTC, address(this), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function add_liquidity(uint256[3] memory amounts, uint256 _min_mint_amount) external; } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } interface IConvex is IERC20{ function withdrawAndUnwrap(uint256 _amount) external; //deposit a curve token function deposit(uint256 _amount, address _to) external; } contract ThreeCryptoLevSwapper { using BoringMath for uint256; using BoringERC20 for IERC20; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); CurvePool constant public threecrypto = CurvePool(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46); IConvex public constant cvx3Crypto = IConvex(0x5958A8DB7dfE0CC49382209069b00F54e17929C2); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant CurveToken = IERC20(0xc4AD29ba4B3c580e6D59105FFf484999997675Ff); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(threecrypto), type(uint256).max); CurveToken.approve(address(cvx3Crypto), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); uint256 amountIntermediate = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this)); uint256[3] memory amountsAdded = [amountIntermediate, 0, 0]; threecrypto.add_liquidity(amountsAdded, 0); uint256 amountTo = CurveToken.balanceOf(address(this)); cvx3Crypto.deposit(amountTo, address(bentoBox)); (, shareReturned) = bentoBox.deposit(cvx3Crypto, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver ) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function add_liquidity( address pool, uint256[4] memory amounts, uint256 _min_mint_amount ) external returns (uint256); } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } interface IConvex is IERC20 { function withdrawAndUnwrap(uint256 _amount) external; //deposit a curve token function deposit(uint256 _amount, address _to) external; } contract StkFrax3CrvLevSwapper { using BoringMath for uint256; using BoringERC20 for IERC20; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); CurvePool public constant threePool = CurvePool(0xA79828DF1850E8a3A3064576f380D90aECDD3359); IConvex public immutable stkFrax3Crv; TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant FRAX3CRV = IERC20(0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B); constructor(IConvex _stkFrax3Crv) public { stkFrax3Crv = _stkFrax3Crv; MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(threePool), type(uint256).max); FRAX3CRV.approve(address(_stkFrax3Crv), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); uint256 amountUSDT = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this)); // Pool token order is FRAX, DAI, USDC, USDT uint256[4] memory amountsAdded = [0, 0, 0, amountUSDT]; uint256 frax3CrvAmount = threePool.add_liquidity(address(FRAX3CRV), amountsAdded, 0); stkFrax3Crv.deposit(frax3CrvAmount, address(bentoBox)); (, shareReturned) = bentoBox.deposit(stkFrax3Crv, address(bentoBox), recipient, frax3CrvAmount, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function add_liquidity(uint256[2] memory amounts, uint256 _min_mint_amount) external; } interface IThreeCrypto is CurvePool { function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external; } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } interface IConvex is IERC20{ function withdrawAndUnwrap(uint256 _amount) external; //deposit a curve token function deposit(uint256 _amount, address _to) external; } contract RenCrvLevSwapper { using BoringMath for uint256; using BoringERC20 for IERC20; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool constant public renCrv = CurvePool(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); IThreeCrypto constant public threecrypto = IThreeCrypto(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46); IConvex public constant cvxRen = IConvex(0xB65eDE134521F0EFD4E943c835F450137dC6E83e); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant CurveToken = IERC20(0x49849C98ae39Fff122806C06791Fa73784FB3675); IERC20 public constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(threecrypto), type(uint256).max); WBTC.approve(address(renCrv), type(uint256).max); CurveToken.approve(address(cvxRen), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); uint256 amountOne = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this)); threecrypto.exchange(0, 1, amountOne, 0); uint256 amountIntermediate = WBTC.balanceOf(address(this)); uint256[2] memory amountsAdded = [0, amountIntermediate]; renCrv.add_liquidity(amountsAdded, 0); uint256 amountTo = CurveToken.balanceOf(address(this)); cvxRen.deposit(amountTo, address(bentoBox)); (, shareReturned) = bentoBox.deposit(cvxRen, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@sushiswap/bentobox-sdk/contracts/IStrategy.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; // solhint-disable not-rely-on-time contract SimpleStrategyMock is IStrategy { using BoringMath for uint256; using BoringERC20 for IERC20; IERC20 private immutable token; address private immutable bentoBox; modifier onlyBentoBox() { require(msg.sender == bentoBox, "Ownable: caller is not the owner"); _; } constructor(address bentoBox_, IERC20 token_) public { bentoBox = bentoBox_; token = token_; } // Send the assets to the Strategy and call skim to invest them function skim(uint256) external override onlyBentoBox { // Leave the tokens on the contract return; } // Harvest any profits made converted to the asset and pass them to the caller function harvest(uint256 balance, address) external override onlyBentoBox returns (int256 amountAdded) { amountAdded = int256(token.balanceOf(address(this)).sub(balance)); token.safeTransfer(bentoBox, uint256(amountAdded)); // Add as profit } // Withdraw assets. The returned amount can differ from the requested amount due to rounding or if the request was more than there is. function withdraw(uint256 amount) external override onlyBentoBox returns (uint256 actualAmount) { token.safeTransfer(bentoBox, uint256(amount)); // Add as profit actualAmount = amount; } // Withdraw all assets in the safest way possible. This shouldn't fail. function exit(uint256 balance) external override onlyBentoBox returns (int256 amountAdded) { amountAdded = 0; token.safeTransfer(bentoBox, balance); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface IYearnVault { function deposit(uint256 amount, address recipient) external returns (uint256 shares); } contract YearnLiquidityMigrationHelper { using BoringMath for uint256; using BoringERC20 for IERC20; // Local variables IBentoBoxV1 public immutable bentoBox; constructor(IBentoBoxV1 bentoBox_) public { bentoBox = bentoBox_; } function migrate( IERC20 token, IYearnVault vault, uint256 amount, address recipient ) external { token.approve(address(vault), amount); uint256 shares = vault.deposit(amount, address(bentoBox)); bentoBox.deposit(token, address(bentoBox), recipient, shares, 0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function remove_liquidity_one_coin(uint256 tokenAmount, int128 i, uint256 min_amount, bool use_underlying) external returns(uint256); } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; function balanceOf(address user) external view returns (uint256); } contract YVIBSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); CurvePool constant public IronBank = CurvePool(0x2dded6Da1BF5DBdF597C45fcFaa3194e53EcfeAF); YearnVault constant public YVIB = YearnVault(0x27b7b1ad7288079A66d12350c828D3C00A6F07d7); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(MIM3POOL), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); uint256 amountFrom = YVIB.withdraw(); IronBank.remove_liquidity_one_coin(amountFrom, 2, 0, true); uint256 amountIntermediate = TETHER.balanceOf(address(this)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function remove_liquidity_one_coin(uint256 tokenAmount, int128 i, uint256 min_amount) external returns(uint256); } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; function balanceOf(address user) external view returns (uint256); } interface IWETH is IERC20 { function transfer(address _to, uint256 _value) external returns (bool success); function deposit() external payable; } contract YVCrvStETHSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); IWETH public constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); CurvePool constant public STETH = CurvePool(0xDC24316b9AE028F1497c275EB9192a3Ea0f67022); YearnVault constant public YVSTETH = YearnVault(0xdCD90C7f6324cfa40d7169ef80b12031770B4325); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(MIM3POOL), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } receive() external payable {} // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); { uint256 amountFrom = YVSTETH.withdraw(); STETH.remove_liquidity_one_coin(amountFrom, 0, 0); } uint256 amountSecond = address(this).balance; WETH.deposit{value: amountSecond}(); WETH.transfer(address(pair), amountSecond); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountIntermediate = getAmountOut(amountSecond, reserve0, reserve1); pair.swap(0, amountIntermediate, address(this), new bytes(0)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface SushiBar { function leave(uint256 share) external; } interface Sushi is IERC20 { function transfer(address _to, uint256 _value) external returns (bool success); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract YVXSushiSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public immutable bentoBox; CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); SushiBar public constant xSushi = SushiBar(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272); Sushi public constant SUSHI = Sushi(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); IUniswapV2Pair constant SUSHI_WETH = IUniswapV2Pair(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); constructor( IBentoBoxV1 bentoBox_ ) public { bentoBox = bentoBox_; TETHER.approve(address(MIM3POOL), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { { (uint256 amountXSushiFrom, ) = bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); xSushi.leave(amountXSushiFrom); } uint256 amountFirst; { uint256 amountFrom = SUSHI.balanceOf(address(this)); SUSHI.transfer(address(SUSHI_WETH), amountFrom); (uint256 reserve0, uint256 reserve1, ) = SUSHI_WETH.getReserves(); amountFirst = getAmountOut(amountFrom, reserve0, reserve1); } SUSHI_WETH.swap(0, amountFirst, address(pair), new bytes(0)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1); pair.swap(0, amountIntermediate, address(this), new bytes(0)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "../../libraries/UniswapV2Library.sol"; interface IxBOO { function leave(uint256 share) external; } interface IBoo is IERC20 { function transfer(address _to, uint256 _value) external returns (bool success); } interface ICurvePool { function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } contract xBooSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0x74A0BcA2eeEdf8883cb91E37e9ff49430f20a616); IUniswapV2Pair constant USDC_WFTM = IUniswapV2Pair(0x2b4C76d0dc16BE1C31D4C1DC53bF9B45987Fc75c); IERC20 constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83); IERC20 constant USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75); IxBOO constant xBOO = IxBOO(0xa48d959AE2E88f1dAA7D5F611E01908106dE7598); IBoo constant BOO = IBoo(0x841FAD6EAe12c286d1Fd18d1d525DFfA75C7EFFE); IUniswapV2Pair constant BOO_FTM = IUniswapV2Pair(0xEc7178F4C41f346b2721907F5cF7628E388A7a58); IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1); ICurvePool public constant ThreeCrypto = ICurvePool(0x2dd7C9371965472E5A5fD28fbE165007c61439E1); constructor() public { USDC.approve(address(ThreeCrypto), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { { (uint256 amountXbooFrom,) = bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); xBOO.leave(amountXbooFrom); } uint256 amountFirst; { uint256 amountFrom = BOO.balanceOf(address(this)); BOO.transfer(address(BOO_FTM), amountFrom); (address token0, ) = UniswapV2Library.sortTokens(address(BOO), address(WFTM)); (uint256 reserve0, uint256 reserve1, ) = BOO_FTM.getReserves(); (reserve0, reserve1) = address(BOO) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountFirst = getAmountOut(amountFrom, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(BOO) == token0 ? (uint256(0), amountFirst) : (amountFirst, uint256(0)); BOO_FTM.swap(amount0Out, amount1Out, address(USDC_WFTM), new bytes(0)); } uint256 amountIntermediate; { (address token0, ) = UniswapV2Library.sortTokens(address(WFTM), address(USDC)); (uint256 reserve0, uint256 reserve1, ) = USDC_WFTM.getReserves(); (reserve0, reserve1) = address(WFTM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(WFTM) == token0 ? (uint256(0), amountIntermediate) : (amountIntermediate, uint256(0)); USDC_WFTM.swap(amount0Out, amount1Out, address(this), new bytes(0)); } uint256 amountTo = ThreeCrypto.exchange(2, 0, amountIntermediate, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "../../libraries/UniswapV2Library.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface IWMEMO is IERC20 { function wrap( uint _amount ) external returns ( uint ); function unwrap( uint _amount ) external returns ( uint ); function transfer(address _to, uint256 _value) external returns (bool success); } interface ITIME is IERC20 { function transfer(address _to, uint256 _value) external returns (bool success); } interface IStakingManager { function unstake( uint _amount, bool _trigger ) external; function stake( uint _amount, address _recipient ) external returns ( bool ); } contract wMEMOSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xf4F46382C2bE1603Dc817551Ff9A7b333Ed1D18f); IUniswapV2Pair constant WMEMO_MIM = IUniswapV2Pair(0x4d308C46EA9f234ea515cC51F16fba776451cac8); IERC20 public constant MIM = IERC20(0x130966628846BFd36ff31a822705796e8cb8C18D); IERC20 public constant MEMO = IERC20(0x136Acd46C134E8269052c62A67042D6bDeDde3C9); IWMEMO public constant WMEMO = IWMEMO(0x0da67235dD5787D67955420C84ca1cEcd4E5Bb3b); IStakingManager public constant STAKING_MANAGER = IStakingManager(0x4456B87Af11e87E329AB7d7C7A246ed1aC2168B9); ITIME public constant TIME = ITIME(0xb54f16fB19478766A268F172C9480f8da1a7c9C3); address private constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7; constructor( ) public { MEMO.approve(address(STAKING_MANAGER), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an outpxut amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(WMEMO_MIM), 0, shareFrom); (address token0, ) = UniswapV2Library.sortTokens(address(WMEMO), address(WMEMO_MIM)); (uint256 reserve0, uint256 reserve1, ) = WMEMO_MIM.getReserves(); (reserve0, reserve1) = address(WMEMO) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); uint256 amountTo = getAmountOut(amountFrom, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(WMEMO) == token0 ? (uint256(0), amountTo) : (amountTo, uint256(0)); WMEMO_MIM.swap(amount0Out, amount1Out, address(bentoBox), new bytes(0)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "../../libraries/UniswapV2Library.sol"; interface CurvePool { function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } contract ICESwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); IERC20 public constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83); IUniswapV2Pair public constant ICE_FTM = IUniswapV2Pair(0x84311ECC54D7553378c067282940b0fdfb913675); IUniswapV2Pair public constant USDC_FTM = IUniswapV2Pair(0x2b4C76d0dc16BE1C31D4C1DC53bF9B45987Fc75c); IERC20 public constant ICE = IERC20(0xf16e81dce15B08F326220742020379B855B87DF9); IERC20 public constant USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75); IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1); CurvePool public constant threePool = CurvePool(0x2dd7C9371965472E5A5fD28fbE165007c61439E1); uint8 private constant USDC_COIN = 2; uint8 private constant MIM_COIN = 0; constructor( ) public { USDC.approve(address(threePool), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(ICE, address(this), address(ICE_FTM), 0, shareFrom); uint256 amountIntermediate; { (address token0, ) = UniswapV2Library.sortTokens(address(ICE), address(WFTM)); (uint256 reserve0, uint256 reserve1, ) = ICE_FTM.getReserves(); (reserve0, reserve1) = address(ICE) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountIntermediate = getAmountOut(amountFrom, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(ICE) == token0 ? (uint256(0), amountIntermediate) : (amountIntermediate, uint256(0)); ICE_FTM.swap(amount0Out, amount1Out, address(USDC_FTM), new bytes(0)); } uint256 amountIntermediate2; { (address token0, ) = UniswapV2Library.sortTokens(address(USDC), address(WFTM)); (uint256 reserve0, uint256 reserve1, ) = USDC_FTM.getReserves(); (reserve0, reserve1) = address(WFTM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountIntermediate2 = getAmountOut(amountIntermediate, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(WFTM) == token0 ? (uint256(0), amountIntermediate2) : (amountIntermediate2, uint256(0)); USDC_FTM.swap(amount0Out, amount1Out, address(this), new bytes(0)); } uint256 amountTo = threePool.exchange(USDC_COIN, MIM_COIN, amountIntermediate2, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(MIM, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "../../libraries/UniswapV2Library.sol"; interface ICurvePool { function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } contract FTMDegenSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0x74A0BcA2eeEdf8883cb91E37e9ff49430f20a616); IUniswapV2Pair constant USDC_WFTM = IUniswapV2Pair(0x2b4C76d0dc16BE1C31D4C1DC53bF9B45987Fc75c); IERC20 constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83); IERC20 constant USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75); IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1); ICurvePool public constant ThreeCrypto = ICurvePool(0x2dd7C9371965472E5A5fD28fbE165007c61439E1); constructor() public { USDC.approve(address(ThreeCrypto), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom,) = bentoBox.withdraw(fromToken, address(this), address(USDC_WFTM), 0, shareFrom); uint256 amountFirst; { (address token0, ) = UniswapV2Library.sortTokens(address(WFTM), address(USDC)); (uint256 reserve0, uint256 reserve1, ) = USDC_WFTM.getReserves(); (reserve0, reserve1) = address(WFTM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountFirst = getAmountOut(amountFrom, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(WFTM) == token0 ? (uint256(0), amountFirst) : (amountFirst, uint256(0)); USDC_WFTM.swap(amount0Out, amount1Out, address(this), new bytes(0)); } uint256 amountTo = ThreeCrypto.exchange(2, 0, amountFirst, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "../../libraries/UniswapV2Library.sol"; contract ArbEthSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0x74c764D41B77DBbb4fe771daB1939B00b146894A); IUniswapV2Pair constant pair = IUniswapV2Pair(0xb6DD51D5425861C808Fd60827Ab6CFBfFE604959); IERC20 constant WETH = IERC20(0x82aF49447D8a07e3bd95BD0d56f35241523fBab1); IERC20 public constant MIM = IERC20(0xFEa7a6a0B346362BF88A9e4A88416B77a57D6c2A); // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom,) = bentoBox.withdraw(fromToken, address(this), address(pair), 0, shareFrom); (address token0, ) = UniswapV2Library.sortTokens(address(MIM), address(WETH)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (reserve0, reserve1) = address(WETH) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); uint256 amountTo = getAmountOut(amountFrom, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(WETH) == token0 ? (uint256(0), amountTo) : (amountTo, uint256(0)); pair.swap(amount0Out, amount1Out, address(bentoBox), new bytes(0)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "../../libraries/UniswapV2Library.sol"; interface ICurvePool { function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface IxBOO is IERC20 { function leave(uint256 share) external; function enter(uint256 amount) external; function transfer(address _to, uint256 _value) external returns (bool success); } contract xBooLevSwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0x74A0BcA2eeEdf8883cb91E37e9ff49430f20a616); IUniswapV2Pair constant USDC_WFTM = IUniswapV2Pair(0x2b4C76d0dc16BE1C31D4C1DC53bF9B45987Fc75c); IERC20 constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83); IERC20 constant USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75); IxBOO constant xBOO = IxBOO(0xa48d959AE2E88f1dAA7D5F611E01908106dE7598); IERC20 constant BOO = IERC20(0x841FAD6EAe12c286d1Fd18d1d525DFfA75C7EFFE); IUniswapV2Pair constant BOO_FTM = IUniswapV2Pair(0xEc7178F4C41f346b2721907F5cF7628E388A7a58); IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1); ICurvePool public constant ThreeCrypto = ICurvePool(0x2dd7C9371965472E5A5fD28fbE165007c61439E1); constructor() public { MIM.approve(address(ThreeCrypto), type(uint256).max); BOO.approve(address(xBOO), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); uint256 amountIntermediate; { uint256 amountFirst = ThreeCrypto.exchange(0, 2, amountFrom, 0, address(USDC_WFTM)); (address token0, ) = UniswapV2Library.sortTokens(address(USDC), address(WFTM)); (uint256 reserve0, uint256 reserve1, ) = USDC_WFTM.getReserves(); (reserve0, reserve1) = address(USDC) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(USDC) == token0 ? (uint256(0), amountIntermediate) : (amountIntermediate, uint256(0)); USDC_WFTM.swap(amount0Out, amount1Out, address(BOO_FTM), new bytes(0)); } uint256 amountIntermediate2; { (address token0, ) = UniswapV2Library.sortTokens(address(BOO), address(WFTM)); (uint256 reserve0, uint256 reserve1, ) = BOO_FTM.getReserves(); (reserve0, reserve1) = address(WFTM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountIntermediate2 = getAmountOut(amountIntermediate, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(WFTM) == token0 ? (uint256(0), amountIntermediate2) : (amountIntermediate2, uint256(0)); BOO_FTM.swap(amount0Out, amount1Out, address(this), new bytes(0)); } xBOO.enter(amountIntermediate2); uint256 amountTo = xBOO.balanceOf(address(this)); xBOO.transfer(address(bentoBox), amountTo); (, shareReturned) = bentoBox.deposit(xBOO, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "../../libraries/UniswapV2Library.sol"; interface IWMEMO is IERC20 { function wrap( uint _amount ) external returns ( uint ); function unwrap( uint _amount ) external returns ( uint ); function transfer(address _to, uint256 _value) external returns (bool success); } interface IStakingManager { function unstake( uint _amount, bool _trigger ) external; function stake( uint _amount, address _recipient ) external returns ( bool ); function claim ( address _recipient ) external; } contract wMEMOLevSwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xf4F46382C2bE1603Dc817551Ff9A7b333Ed1D18f); IUniswapV2Pair constant WMEMO_MIM = IUniswapV2Pair(0x4d308C46EA9f234ea515cC51F16fba776451cac8); IERC20 public constant MIM = IERC20(0x130966628846BFd36ff31a822705796e8cb8C18D); IERC20 public constant MEMO = IERC20(0x136Acd46C134E8269052c62A67042D6bDeDde3C9); IWMEMO public constant WMEMO = IWMEMO(0x0da67235dD5787D67955420C84ca1cEcd4E5Bb3b); IStakingManager public constant STAKING_MANAGER = IStakingManager(0x4456B87Af11e87E329AB7d7C7A246ed1aC2168B9); IERC20 public constant TIME = IERC20(0xb54f16fB19478766A268F172C9480f8da1a7c9C3); address private constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7; constructor( ) public { TIME.approve(address(STAKING_MANAGER), type(uint256).max); MEMO.approve(address(WMEMO), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountMIMFrom, ) = bentoBox.withdraw(MIM, address(this), address(WMEMO_MIM), 0, shareFrom); (address token0, ) = UniswapV2Library.sortTokens(address(WMEMO), address(MIM)); (uint256 reserve0, uint256 reserve1, ) = WMEMO_MIM.getReserves(); (reserve0, reserve1) = address(MIM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); uint256 amountTo = getAmountOut(amountMIMFrom, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(MIM) == token0 ? (uint256(0), amountTo) : (amountTo, uint256(0)); WMEMO_MIM.swap(amount0Out, amount1Out, address(bentoBox), new bytes(0)); (, shareReturned) = bentoBox.deposit(WMEMO, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "../../libraries/UniswapV2Library.sol"; interface CurvePool { function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } contract ICELevSwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); IERC20 public constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83); IUniswapV2Pair public constant ICE_FTM = IUniswapV2Pair(0x84311ECC54D7553378c067282940b0fdfb913675); IUniswapV2Pair public constant USDC_FTM = IUniswapV2Pair(0x2b4C76d0dc16BE1C31D4C1DC53bF9B45987Fc75c); IERC20 public constant ICE = IERC20(0xf16e81dce15B08F326220742020379B855B87DF9); IERC20 public constant USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75); IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1); CurvePool public constant threePool = CurvePool(0x2dd7C9371965472E5A5fD28fbE165007c61439E1); uint8 private constant USDC_COIN = 2; uint8 private constant MIM_COIN = 0; constructor( ) public { MIM.approve(address(threePool), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); uint256 amountIntermediate = threePool.exchange(MIM_COIN, USDC_COIN, amountFrom, 0, address(USDC_FTM)); uint256 amountIntermediate2; { (address token0, ) = UniswapV2Library.sortTokens(address(USDC), address(WFTM)); (uint256 reserve0, uint256 reserve1, ) = USDC_FTM.getReserves(); (reserve0, reserve1) = address(USDC) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountIntermediate2 = getAmountOut(amountIntermediate, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(USDC) == token0 ? (uint256(0), amountIntermediate2) : (amountIntermediate2, uint256(0)); USDC_FTM.swap(amount0Out, amount1Out, address(ICE_FTM), new bytes(0)); } uint256 amountTo; { (address token0, ) = UniswapV2Library.sortTokens(address(ICE), address(WFTM)); (uint256 reserve0, uint256 reserve1, ) = ICE_FTM.getReserves(); (reserve0, reserve1) = address(WFTM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountTo = getAmountOut(amountIntermediate2, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(WFTM) == token0 ? (uint256(0), amountTo) : (amountTo, uint256(0)); ICE_FTM.swap(amount0Out, amount1Out, address(bentoBox), new bytes(0)); } (, shareReturned) = bentoBox.deposit(ICE, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "../../libraries/UniswapV2Library.sol"; interface ICurvePool { function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } contract FTMLevDegenSwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0x74A0BcA2eeEdf8883cb91E37e9ff49430f20a616); IUniswapV2Pair constant USDC_WFTM = IUniswapV2Pair(0x2b4C76d0dc16BE1C31D4C1DC53bF9B45987Fc75c); IERC20 constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83); IERC20 constant USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75); IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1); ICurvePool public constant ThreeCrypto = ICurvePool(0x2dd7C9371965472E5A5fD28fbE165007c61439E1); constructor() public { MIM.approve(address(ThreeCrypto), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { uint256 amountFirst; { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); amountFirst = ThreeCrypto.exchange(0, 2, amountFrom, 0, address(USDC_WFTM)); } uint256 amountTo; { (address token0, ) = UniswapV2Library.sortTokens(address(USDC), address(WFTM)); (uint256 reserve0, uint256 reserve1, ) = USDC_WFTM.getReserves(); (reserve0, reserve1) = address(USDC) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountTo = getAmountOut(amountFirst, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(USDC) == token0 ? (uint256(0), amountTo) : (amountTo, uint256(0)); USDC_WFTM.swap(amount0Out, amount1Out, address(bentoBox), new bytes(0)); } (, shareReturned) = bentoBox.deposit(WFTM, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "../../libraries/UniswapV2Library.sol"; contract ArbEthLevSwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0x74c764D41B77DBbb4fe771daB1939B00b146894A); IUniswapV2Pair constant pair = IUniswapV2Pair(0xb6DD51D5425861C808Fd60827Ab6CFBfFE604959); IERC20 constant WETH = IERC20(0x82aF49447D8a07e3bd95BD0d56f35241523fBab1); IERC20 public constant MIM = IERC20(0xFEa7a6a0B346362BF88A9e4A88416B77a57D6c2A); // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(pair), 0, shareFrom); (address token0, ) = UniswapV2Library.sortTokens(address(MIM), address(WETH)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (reserve0, reserve1) = address(MIM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); uint256 amountTo = getAmountOut(amountFrom, reserve0, reserve1); (uint256 amount0Out, uint256 amount1Out) = address(MIM) == token0 ? (uint256(0), amountTo) : (amountTo, uint256(0)); pair.swap(amount0Out, amount1Out, address(bentoBox), new bytes(0)); (, shareReturned) = bentoBox.deposit(WETH, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import './libraries/SafeMath.sol'; contract UniswapV2ERC20 { using SafeMathUniswap for uint; string public constant name = 'SushiSwap LP Token'; string public constant symbol = 'SLP'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'UniswapV2: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE'); _approve(owner, spender, value); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import './UniswapV2ERC20.sol'; import './libraries/Math.sol'; import './libraries/UQ112x112.sol'; import './interfaces/IERC20.sol'; import './interfaces/IUniswapV2Factory.sol'; import './interfaces/IUniswapV2Callee.sol'; interface IMigrator { // Return the desired amount of liquidity token that the migrator wants. function desiredLiquidity() external view returns (uint256); } contract UniswapV2Pair is UniswapV2ERC20 { using SafeMathUniswap for uint; using UQ112x112 for uint224; uint public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint public price0CumulativeLast; uint public price1CumulativeLast; uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'UniswapV2: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED'); } 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); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IUniswapV2Factory(factory).feeTo(); feeOn = feeTo != address(0); uint _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)); uint denominator = rootK.mul(5).add(rootKLast); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint liquidity) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings uint balance0 = IERC20Uniswap(token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { address migrator = IUniswapV2Factory(factory).migrator(); if (msg.sender == migrator) { liquidity = IMigrator(migrator).desiredLiquidity(); require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity"); } else { require(migrator == address(0), "Must not have migrator"); liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } } else { liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint amount0, uint amount1) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K'); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IERC20Uniswap { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@sushiswap/core/contracts/uniswapv2/UniswapV2Pair.sol"; contract SushiSwapPairMock is UniswapV2Pair { constructor() public UniswapV2Pair() { return; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import './interfaces/IUniswapV2Factory.sol'; import './UniswapV2Pair.sol'; contract UniswapV2Factory is IUniswapV2Factory { address public override feeTo; address public override feeToSetter; address public override migrator; mapping(address => mapping(address => address)) public override getPair; address[] public override allPairs; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; } function allPairsLength() external override view returns (uint) { return allPairs.length; } function pairCodeHash() external pure returns (bytes32) { return keccak256(type(UniswapV2Pair).creationCode); } function createPair(address tokenA, address tokenB) external override returns (address pair) { require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(UniswapV2Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } UniswapV2Pair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address _feeTo) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); feeTo = _feeTo; } function setMigrator(address _migrator) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); migrator = _migrator; } function setFeeToSetter(address _feeToSetter) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); feeToSetter = _feeToSetter; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/UniswapV2Factory.sol"; contract SushiSwapFactoryMock is UniswapV2Factory { constructor() public UniswapV2Factory(msg.sender) { return; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface IWOHM { function wrap( uint _amount ) external returns ( uint ); function unwrap( uint _amount ) external returns ( uint ); } interface IOHM is IERC20 { function transfer(address _to, uint256 _value) external returns (bool success); } interface IStakingManager { function unstake( uint _amount, bool _trigger ) external; function stake( uint _amount, address _recipient ) external returns ( bool ); } contract wOHMSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); IERC20 public constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IUniswapV2Pair constant OHM_DAI = IUniswapV2Pair(0x34d7d7Aaf50AD4944B70B320aCB24C95fa2def7c); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant SOHM = IERC20(0x04F2694C8fcee23e8Fd0dfEA1d4f5Bb8c352111F); IWOHM public constant WOHM = IWOHM(0xCa76543Cf381ebBB277bE79574059e32108e3E65); IStakingManager public constant STAKING_MANAGER = IStakingManager(0xFd31c7d00Ca47653c6Ce64Af53c1571f9C36566a); IOHM public constant OHM = IOHM(0x383518188C0C6d7730D91b2c03a03C837814a899); constructor( ) public { DAI.approve(address(MIM3POOL), type(uint256).max); SOHM.approve(address(STAKING_MANAGER), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { uint256 amountFirst; { (uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); amountFirst = WOHM.unwrap(amountFrom); } STAKING_MANAGER.unstake(amountFirst, false); OHM.transfer(address(OHM_DAI), amountFirst); (uint256 reserve0, uint256 reserve1, ) = OHM_DAI.getReserves(); uint256 amountDAI = getAmountOut(amountFirst, reserve0, reserve1); OHM_DAI.swap(0, amountDAI, address(this), new bytes(0)); uint256 amountTo = MIM3POOL.exchange_underlying(1, 0, amountDAI, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function remove_liquidity_one_coin(uint256 tokenAmount, int128 i, uint256 min_amount) external; } interface IThreeCrypto is CurvePool { function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external; } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; function balanceOf(address user) external view returns (uint256); } interface IConvex is IERC20{ function withdrawAndUnwrap(uint256 _amount) external; } contract WethSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant degenBox = IBentoBoxV1(0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); IThreeCrypto constant public threecrypto = IThreeCrypto(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(MIM3POOL), type(uint256).max); WETH.approve(address(threecrypto), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = degenBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); threecrypto.exchange(2, 0, amountFrom, 0); uint256 amountIntermediate = TETHER.balanceOf(address(this)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(degenBox)); (, shareReturned) = degenBox.deposit(toToken, address(degenBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function remove_liquidity_one_coin(uint256 tokenAmount, int128 i, uint256 min_amount) external; } interface IThreeCrypto is CurvePool { function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external; } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; function balanceOf(address user) external view returns (uint256); } interface IConvex is IERC20{ function withdrawAndUnwrap(uint256 _amount) external; } contract WbtcSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant degenBox = IBentoBoxV1(0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); IThreeCrypto constant public threecrypto = IThreeCrypto(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(MIM3POOL), type(uint256).max); WBTC.approve(address(threecrypto), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = degenBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); threecrypto.exchange(1, 0, amountFrom, 0); uint256 amountIntermediate = TETHER.balanceOf(address(this)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(degenBox)); (, shareReturned) = degenBox.deposit(toToken, address(degenBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function remove_liquidity_one_coin(uint256 tokenAmount, uint256 i, uint256 min_amount) external; } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; function balanceOf(address user) external view returns (uint256); } interface IConvex is IERC20{ function withdrawAndUnwrap(uint256 _amount) external; } contract ThreeCryptoSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); CurvePool constant public threecrypto = CurvePool(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46); IConvex public constant cvx3Crypto = IConvex(0x5958A8DB7dfE0CC49382209069b00F54e17929C2); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(MIM3POOL), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); cvx3Crypto.withdrawAndUnwrap(amountFrom); threecrypto.remove_liquidity_one_coin(amountFrom, 0, 0); uint256 amountIntermediate = TETHER.balanceOf(address(this)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "../../interfaces/ISwapper.sol"; interface CurvePool { function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver ) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function remove_liquidity_one_coin( address pool, uint256 tokenAmount, int128 i, uint256 min_amount ) external returns (uint256); } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; function balanceOf(address user) external view returns (uint256); } interface IConvex is IERC20 { function withdrawAndUnwrap(uint256 _amount) external; } contract StkFrax3CrvSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); address public constant FRAX3CRVPOOL = 0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B; CurvePool public constant threePool = CurvePool(0xA79828DF1850E8a3A3064576f380D90aECDD3359); IConvex public immutable stkFrax3Crv; TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant FRAX3CRV = IERC20(0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B); constructor(IConvex _stkFrax3Crv) public { stkFrax3Crv = _stkFrax3Crv; MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(MIM3POOL), type(uint256).max); FRAX3CRV.approve(address(threePool), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20, IERC20, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(IERC20(stkFrax3Crv), address(this), address(this), 0, shareFrom); stkFrax3Crv.withdrawAndUnwrap(amountFrom); // Pool token order is FRAX, DAI, USDC, USDT uint256 amountUSDT = threePool.remove_liquidity_one_coin(FRAX3CRVPOOL, amountFrom, 3, 0); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountUSDT, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(MIM, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20, IERC20, address, address, uint256, uint256 ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0, 0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface IsSpell { function burn(address to, uint256 shares) external returns (bool); } interface ISpell is IERC20 { function transfer(address _to, uint256 _value) external returns (bool success); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract SSpellSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IsSpell public constant sSpell = IsSpell(0x26FA3fFFB6EfE8c1E69103aCb4044C26B9A106a9); ISpell public constant SPELL = ISpell(0x090185f2135308BaD17527004364eBcC2D37e5F6); IUniswapV2Pair constant SPELL_ETH = IUniswapV2Pair(0xb5De0C3753b6E1B4dBA616Db82767F17513E6d4E); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); constructor( ) public { TETHER.approve(address(MIM3POOL), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { { (uint256 amountSSpellFrom, ) = bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); sSpell.burn(address(this), amountSSpellFrom); } uint256 amountFirst; { uint256 amountFrom = SPELL.balanceOf(address(this)); SPELL.transfer(address(SPELL_ETH), amountFrom); (uint256 reserve0, uint256 reserve1, ) = SPELL_ETH.getReserves(); amountFirst = getAmountOut(amountFrom, reserve0, reserve1); } SPELL_ETH.swap(0, amountFirst, address(pair), new bytes(0)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1); pair.swap(0, amountIntermediate, address(this), new bytes(0)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface IsSpell { function burn(address to, uint256 shares) external returns (bool); } interface ISpell is IERC20 { function transfer(address _to, uint256 _value) external returns (bool success); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract SpellSuperSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IsSpell public constant sSpell = IsSpell(0x26FA3fFFB6EfE8c1E69103aCb4044C26B9A106a9); ISpell public constant SPELL = ISpell(0x090185f2135308BaD17527004364eBcC2D37e5F6); IUniswapV2Pair constant SPELL_ETH = IUniswapV2Pair(0xb5De0C3753b6E1B4dBA616Db82767F17513E6d4E); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); constructor( ) public { TETHER.approve(address(MIM3POOL), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(SPELL_ETH), 0, shareFrom); uint256 amountFirst; { (uint256 reserve0, uint256 reserve1, ) = SPELL_ETH.getReserves(); amountFirst = getAmountOut(amountFrom, reserve0, reserve1); } SPELL_ETH.swap(0, amountFirst, address(pair), new bytes(0)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1); pair.swap(0, amountIntermediate, address(this), new bytes(0)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function remove_liquidity_one_coin(uint256 tokenAmount, int128 i, uint256 min_amount) external; } interface IThreeCrypto is CurvePool { function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external; } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; function balanceOf(address user) external view returns (uint256); } interface IConvex is IERC20{ function withdrawAndUnwrap(uint256 _amount) external; } contract RenCrvSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool constant public renCrv = CurvePool(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); IThreeCrypto constant public threecrypto = IThreeCrypto(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46); IConvex public constant cvxRen = IConvex(0xB65eDE134521F0EFD4E943c835F450137dC6E83e); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant CurveToken = IERC20(0x49849C98ae39Fff122806C06791Fa73784FB3675); IERC20 public constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); TETHER.approve(address(MIM3POOL), type(uint256).max); WBTC.approve(address(threecrypto), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); cvxRen.withdrawAndUnwrap(amountFrom); renCrv.remove_liquidity_one_coin(amountFrom, 1, 0); uint256 amountOne = WBTC.balanceOf(address(this)); threecrypto.exchange(1, 0, amountOne, 0); uint256 amountIntermediate = TETHER.balanceOf(address(this)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; contract FTMSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); IUniswapV2Pair constant pair = IUniswapV2Pair(0xB32b31DfAfbD53E310390F641C7119b5B9Ea0488); IERC20 constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83); IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1); // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom,) = bentoBox.withdraw(fromToken, address(this), address(pair), 0, shareFrom); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountTo = getAmountOut(amountFrom, reserve0, reserve1); pair.swap(0, amountTo, address(bentoBox), new bytes(0)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../../interfaces/ISwapper.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract ALCXSwapper is ISwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant ALCX = IERC20(0xdBdb4d16EdA451D0503b854CF79D55697F90c8DF); IUniswapV2Pair constant ALCX_WETH = IUniswapV2Pair(0xC3f279090a47e80990Fe3a9c30d24Cb117EF91a8); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); constructor() public { TETHER.approve(address(MIM3POOL), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount /// @inheritdoc ISwapper function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(ALCX_WETH), 0, shareFrom); (uint256 reserve0, uint256 reserve1, ) = ALCX_WETH.getReserves(); uint256 amountFirst = getAmountOut(amountFrom, reserve1, reserve0); ALCX_WETH.swap(amountFirst, 0, address(pair), new bytes(0)); (reserve0, reserve1, ) = pair.getReserves(); uint256 amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1); pair.swap(0, amountIntermediate, address(this), new bytes(0)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } // Swaps to an exact amount, from a flexible input amount /// @inheritdoc ISwapper function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) public override returns (uint256 shareUsed, uint256 shareReturned) { return (0,0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract YVYFILevSwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public immutable bentoBox; CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); YearnVault public constant YFI_VAULT = YearnVault(0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IUniswapV2Pair constant YFI_WETH = IUniswapV2Pair(0x088ee5007C98a9677165D78dD2109AE4a3D04d0C); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); IERC20 constant YFI = IERC20(0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); constructor( IBentoBoxV1 bentoBox_ ) public { bentoBox = bentoBox_; MIM.approve(address(MIM3POOL), type(uint256).max); YFI.approve(address(YFI_VAULT), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { uint256 amountFirst; { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); amountFirst = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(pair)); } uint256 amountIntermediate; { (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0); pair.swap(amountIntermediate, 0, address(YFI_WETH), new bytes(0)); } (uint256 reserve0, uint256 reserve1, ) = YFI_WETH.getReserves(); uint256 amountInt2 = getAmountOut(amountIntermediate, reserve1, reserve0); YFI_WETH.swap(amountInt2, 0, address(this), new bytes(0)); uint256 amountTo = YFI_VAULT.deposit(type(uint256).max, address(bentoBox)); (, shareReturned) = bentoBox.deposit(IERC20(address(YFI_VAULT)), address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface SushiBar is IERC20 { function leave(uint256 share) external; function enter(uint256 amount) external; function transfer(address _to, uint256 _value) external returns (bool success); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract YVXSushiLevSwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public immutable bentoBox; CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); SushiBar public constant xSushi = SushiBar(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272); IERC20 public constant SUSHI = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); IUniswapV2Pair constant SUSHI_WETH = IUniswapV2Pair(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); constructor( IBentoBoxV1 bentoBox_ ) public { bentoBox = bentoBox_; SUSHI.approve(address(xSushi), type(uint256).max); MIM.approve(address(MIM3POOL), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { uint256 amountFirst; uint256 amountIntermediate; { (uint256 amountMIMFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); amountFirst = MIM3POOL.exchange_underlying(0, 3, amountMIMFrom, 0, address(pair)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0); } uint256 amountThird; { pair.swap(amountIntermediate, 0, address(SUSHI_WETH), new bytes(0)); (uint256 reserve0, uint256 reserve1, ) = SUSHI_WETH.getReserves(); amountThird = getAmountOut(amountIntermediate, reserve1, reserve0); } SUSHI_WETH.swap(amountThird, 0, address(this), new bytes(0)); xSushi.enter(amountThird); uint256 amountTo = xSushi.balanceOf(address(this)); xSushi.transfer(address(bentoBox), amountTo); (, shareReturned) = bentoBox.deposit(xSushi, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface YearnVault { function withdraw() external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract YVWETHLevSwapper{ using BoringMath for uint256; // Local variables IBentoBoxV1 public immutable bentoBox; CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); YearnVault public constant WETH_VAULT = YearnVault(0xa258C4606Ca8206D8aA700cE2143D7db854D168c); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); IERC20 constant WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); constructor( IBentoBoxV1 bentoBox_ ) public { bentoBox = bentoBox_; WETH.approve(address(WETH_VAULT), type(uint256).max); MIM.approve(address(MIM3POOL), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); uint256 amountIntermediate = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(pair)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInt2 = getAmountOut(amountIntermediate, reserve1, reserve0); pair.swap(amountInt2, 0, address(this), new bytes(0)); uint256 amountTo = WETH_VAULT.deposit(type(uint256).max, address(bentoBox)); (, shareReturned) = bentoBox.deposit(IERC20(address(WETH_VAULT)), address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface IWOHM is IERC20 { function wrap( uint _amount ) external returns ( uint ); function unwrap( uint _amount ) external returns ( uint ); function transfer(address _to, uint256 _value) external returns (bool success); } interface IStakingManager { function unstake( uint _amount, bool _trigger ) external; function stake( uint _amount, address _recipient ) external returns ( bool ); function claim ( address _recipient ) external; } contract wOHMLevSwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); IUniswapV2Pair constant OHM_DAI = IUniswapV2Pair(0x34d7d7Aaf50AD4944B70B320aCB24C95fa2def7c); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); IERC20 public constant SOHM = IERC20(0x04F2694C8fcee23e8Fd0dfEA1d4f5Bb8c352111F); IWOHM public constant WOHM = IWOHM(0xCa76543Cf381ebBB277bE79574059e32108e3E65); IStakingManager public constant STAKING_MANAGER = IStakingManager(0xFd31c7d00Ca47653c6Ce64Af53c1571f9C36566a); IERC20 public constant OHM = IERC20(0x383518188C0C6d7730D91b2c03a03C837814a899); constructor( ) public { MIM.approve(address(MIM3POOL), type(uint256).max); OHM.approve(address(STAKING_MANAGER), type(uint256).max); SOHM.approve(address(WOHM), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { uint256 amountFirst; uint256 amountIntermediate; { (uint256 amountMIMFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); amountFirst = MIM3POOL.exchange_underlying(0, 1, amountMIMFrom, 0, address(OHM_DAI)); (uint256 reserve0, uint256 reserve1, ) = OHM_DAI.getReserves(); amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0); } OHM_DAI.swap(amountIntermediate, 0, address(this), new bytes(0)); STAKING_MANAGER.stake(amountIntermediate, address(this)); STAKING_MANAGER.claim(address(this)); uint256 amountTo = WOHM.wrap(amountIntermediate); WOHM.transfer(address(bentoBox), amountTo); (, shareReturned) = bentoBox.deposit(WOHM, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract SpellLevSwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant SPELL = IERC20(0x090185f2135308BaD17527004364eBcC2D37e5F6); IUniswapV2Pair constant SPELL_ETH = IUniswapV2Pair(0xb5De0C3753b6E1B4dBA616Db82767F17513E6d4E); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); uint256 amountFirst = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(pair)); uint256 amountIntermediate; { (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0); pair.swap(amountIntermediate, 0, address(SPELL_ETH), new bytes(0)); } uint256 amountTo; { (uint256 reserve0, uint256 reserve1, ) = SPELL_ETH.getReserves(); amountTo = getAmountOut(amountIntermediate, reserve1, reserve0); } SPELL_ETH.swap(amountTo, 0, address(bentoBox), new bytes(0)); (, shareReturned) = bentoBox.deposit(SPELL, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; contract FTMLevSwapper{ using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); IUniswapV2Pair constant pair = IUniswapV2Pair(0xB32b31DfAfbD53E310390F641C7119b5B9Ea0488); IERC20 constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83); IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1); // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(pair), 0, shareFrom); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountTo = getAmountOut(amountFrom, reserve1, reserve0); pair.swap(amountTo, 0, address(bentoBox), new bytes(0)); (, shareReturned) = bentoBox.deposit(WFTM, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; interface CurvePool { function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256); } interface TetherToken { function approve(address _spender, uint256 _value) external; } contract ALCXLevSwapper { using BoringMath for uint256; // Local variables IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B); TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 public constant ALCX = IERC20(0xdBdb4d16EdA451D0503b854CF79D55697F90c8DF); IUniswapV2Pair constant ALCX_WETH = IUniswapV2Pair(0xC3f279090a47e80990Fe3a9c30d24Cb117EF91a8); IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553); IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3); constructor() public { MIM.approve(address(MIM3POOL), type(uint256).max); } // Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // Given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // Swaps to a flexible amount, from an exact input amount function swap( address recipient, uint256 shareToMin, uint256 shareFrom ) public returns (uint256 extraShare, uint256 shareReturned) { uint256 amountFirst; uint256 amountIntermediate; { (uint256 amountMIMFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom); amountFirst = MIM3POOL.exchange_underlying(0, 3, amountMIMFrom, 0, address(pair)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0); } pair.swap(amountIntermediate, 0, address(ALCX_WETH), new bytes(0)); (uint256 reserve0, uint256 reserve1, ) = ALCX_WETH.getReserves(); uint256 amountThird = getAmountOut(amountIntermediate, reserve0, reserve1); ALCX_WETH.swap(0, amountThird, address(bentoBox), new bytes(0)); (, shareReturned) = bentoBox.deposit(ALCX, address(bentoBox), recipient, amountThird, 0); extraShare = shareReturned.sub(shareToMin); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../interfaces/IOracle.sol"; // Chainlink Aggregator interface IAggregator { function latestAnswer() external view returns (int256 answer); } interface IYearnVault { function pricePerShare() external view returns (uint256 price); } contract YearnChainlinkOracle is IOracle { using BoringMath for uint256; // Keep everything in uint256 // Calculates the lastest exchange rate // Uses both divide and multiply only for tokens not supported directly by Chainlink, for example MKR/USD function _get( address multiply, address divide, uint256 decimals, address yearnVault ) internal view returns (uint256) { uint256 price = uint256(1e36); if (multiply != address(0)) { price = price.mul(uint256(IAggregator(multiply).latestAnswer())); } else { price = price.mul(1e18); } if (divide != address(0)) { price = price / uint256(IAggregator(divide).latestAnswer()); } // @note decimals have to take into account the decimals of the vault asset return price / decimals.mul(IYearnVault(yearnVault).pricePerShare()); } function getDataParameter( address multiply, address divide, uint256 decimals, address yearnVault ) public pure returns (bytes memory) { return abi.encode(multiply, divide, decimals, yearnVault); } // Get the latest exchange rate /// @inheritdoc IOracle function get(bytes calldata data) public override returns (bool, uint256) { (address multiply, address divide, uint256 decimals, address yearnVault) = abi.decode(data, (address, address, uint256, address)); return (true, _get(multiply, divide, decimals, yearnVault)); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata data) public view override returns (bool, uint256) { (address multiply, address divide, uint256 decimals, address yearnVault) = abi.decode(data, (address, address, uint256, address)); return (true, _get(multiply, divide, decimals, yearnVault)); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (, rate) = peek(data); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "Chainlink"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "LINK"; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../interfaces/IOracle.sol"; import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; interface IAggregator { function latestAnswer() external view returns (int256 answer); } /// @title xSUSHIOracle /// @author BoringCrypto /// @notice Oracle used for getting the price of xSUSHI based on Chainlink /// @dev contract xSUSHIOracle is IOracle { using BoringMath for uint256; // Keep everything in uint256 IERC20 public immutable sushi; IERC20 public immutable bar; IAggregator public immutable sushiOracle; constructor( IERC20 sushi_, IERC20 bar_, IAggregator sushiOracle_ ) public { sushi = sushi_; bar = bar_; sushiOracle = sushiOracle_; } // Calculates the lastest exchange rate // Uses sushi rate and xSUSHI conversion and divide for any conversion other than from SUSHI to ETH function _get(address divide, uint256 decimals) internal view returns (uint256) { uint256 price = uint256(1e36); price = (price.mul(uint256(sushiOracle.latestAnswer())) / bar.totalSupply()).mul(sushi.balanceOf(address(bar))); if (divide != address(0)) { price = price / uint256(IAggregator(divide).latestAnswer()); } return price / decimals; } function getDataParameter(address divide, uint256 decimals) public pure returns (bytes memory) { return abi.encode(divide, decimals); } // Get the latest exchange rate /// @inheritdoc IOracle function get(bytes calldata data) public override returns (bool, uint256) { (address divide, uint256 decimals) = abi.decode(data, (address, uint256)); return (true, _get(divide, decimals)); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata data) public view override returns (bool, uint256) { (address divide, uint256 decimals) = abi.decode(data, (address, uint256)); return (true, _get(divide, decimals)); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (, rate) = peek(data); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "xSUSHI Chainlink"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "xSUSHI-LINK"; } } // SPDX-License-Identifier: AGPL-3.0-only // Using the same Copyleft License as in the original Repository pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../interfaces/IOracle.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../libraries/FixedPoint.sol"; import "hardhat/console.sol"; // solhint-disable not-rely-on-time // adapted from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol interface IAggregator { function latestAnswer() external view returns (int256 answer); } contract xBooOracle is IOracle { using FixedPoint for *; using BoringMath for uint256; uint256 public constant PERIOD = 10 minutes; IAggregator public constant FTM_USD = IAggregator(0xf4766552D15AE4d256Ad41B6cf2933482B0680dc); IUniswapV2Pair public constant BOO_FTM = IUniswapV2Pair(0xEc7178F4C41f346b2721907F5cF7628E388A7a58); IERC20 public constant BOO = IERC20(0x841FAD6EAe12c286d1Fd18d1d525DFfA75C7EFFE); IERC20 public constant XBOO = IERC20(0xa48d959AE2E88f1dAA7D5F611E01908106dE7598); struct PairInfo { uint256 priceCumulativeLast; uint32 blockTimestampLast; uint144 priceAverage; } PairInfo public pairInfo; function _get(uint32 blockTimestamp) public view returns (uint256) { uint256 priceCumulative = BOO_FTM.price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(BOO_FTM).getReserves(); priceCumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * (blockTimestamp - blockTimestampLast); // overflows ok // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed return priceCumulative; } function toXBOO(uint256 amount) internal view returns (uint256) { return amount.mul(BOO.balanceOf(address(XBOO))) / XBOO.totalSupply(); } // Get the latest exchange rate, if no valid (recent) rate is available, return false /// @inheritdoc IOracle function get(bytes calldata) external override returns (bool, uint256) { uint32 blockTimestamp = uint32(block.timestamp); if (pairInfo.blockTimestampLast == 0) { pairInfo.blockTimestampLast = blockTimestamp; pairInfo.priceCumulativeLast = _get(blockTimestamp); return (false, 0); } uint32 timeElapsed = blockTimestamp - pairInfo.blockTimestampLast; // overflow is desired console.log(timeElapsed); if (timeElapsed < PERIOD) { return (true, pairInfo.priceAverage); } uint256 priceCumulative = _get(blockTimestamp); pairInfo.priceAverage = uint144(1e44 / toXBOO(uint256(FixedPoint .uq112x112(uint224((priceCumulative - pairInfo.priceCumulativeLast) / timeElapsed)) .mul(1e18) .decode144())).mul(uint256(FTM_USD.latestAnswer()))); pairInfo.blockTimestampLast = blockTimestamp; pairInfo.priceCumulativeLast = priceCumulative; return (true, pairInfo.priceAverage); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata) public view override returns (bool, uint256) { uint32 blockTimestamp = uint32(block.timestamp); if (pairInfo.blockTimestampLast == 0) { return (false, 0); } uint32 timeElapsed = blockTimestamp - pairInfo.blockTimestampLast; // overflow is desired if (timeElapsed < PERIOD) { return (true, pairInfo.priceAverage); } uint256 priceCumulative = _get(blockTimestamp); uint144 priceAverage = uint144(1e44 / toXBOO(uint256(FixedPoint .uq112x112(uint224((priceCumulative - pairInfo.priceCumulativeLast) / timeElapsed)) .mul(1e18) .decode144())).mul(uint256(FTM_USD.latestAnswer()))); return (true, priceAverage); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata) external view override returns (uint256 rate) { (uint256 reserve0, uint256 reserve1, ) = BOO_FTM.getReserves(); rate = 1e44 / toXBOO(reserve0.mul(1e18) / reserve1).mul(uint256(FTM_USD.latestAnswer())); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "xBOO TWAP"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "xBOO"; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; import "./FullMath_v06_12.sol"; // solhint-disable // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // multiply a UQ112x112 by a uint256, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z = 0; require(y == 0 || (z = self._x * y) / y == self._x, "FixedPoint::mul: overflow"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // lossy if either numerator or denominator is greater than 112 bits function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint::fraction: div by 0"); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), "FixedPoint::fraction: overflow"); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), "FixedPoint::fraction: overflow"); return uq112x112(uint224(result)); } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity 0.6.12; // solhint-disable // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, "FullMath::mulDiv: overflow"); return fullDiv(l, h, d); } } // SPDX-License-Identifier: AGPL-3.0-only // Using the same Copyleft License as in the original Repository pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../interfaces/IOracle.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol"; import "../libraries/FixedPoint.sol"; import "hardhat/console.sol"; // solhint-disable not-rely-on-time // adapted from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol interface IAggregator { function latestAnswer() external view returns (int256 answer); } contract ICEOracleFTM is IOracle { using FixedPoint for *; using BoringMath for uint256; uint256 public constant PERIOD = 10 minutes; IAggregator public constant FTM_USD = IAggregator(0xf4766552D15AE4d256Ad41B6cf2933482B0680dc); IUniswapV2Pair public constant ICE_FTM = IUniswapV2Pair(0x84311ECC54D7553378c067282940b0fdfb913675); IERC20 public constant ICE = IERC20(0xf16e81dce15B08F326220742020379B855B87DF9); struct PairInfo { uint256 priceCumulativeLast; uint32 blockTimestampLast; uint144 priceAverage; } PairInfo public pairInfo; function _get(uint32 blockTimestamp) public view returns (uint256) { uint256 priceCumulative = ICE_FTM.price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(ICE_FTM).getReserves(); priceCumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * (blockTimestamp - blockTimestampLast); // overflows ok // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed return priceCumulative; } // Get the latest exchange rate, if no valid (recent) rate is available, return false /// @inheritdoc IOracle function get(bytes calldata) external override returns (bool, uint256) { uint32 blockTimestamp = uint32(block.timestamp); if (pairInfo.blockTimestampLast == 0) { pairInfo.blockTimestampLast = blockTimestamp; pairInfo.priceCumulativeLast = _get(blockTimestamp); return (false, 0); } uint32 timeElapsed = blockTimestamp - pairInfo.blockTimestampLast; // overflow is desired console.log(timeElapsed); if (timeElapsed < PERIOD) { return (true, pairInfo.priceAverage); } uint256 priceCumulative = _get(blockTimestamp); pairInfo.priceAverage = uint144(1e44 / uint256(FixedPoint .uq112x112(uint224((priceCumulative - pairInfo.priceCumulativeLast) / timeElapsed)) .mul(1e18) .decode144()).mul(uint256(FTM_USD.latestAnswer()))); pairInfo.blockTimestampLast = blockTimestamp; pairInfo.priceCumulativeLast = priceCumulative; return (true, pairInfo.priceAverage); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata) public view override returns (bool, uint256) { uint32 blockTimestamp = uint32(block.timestamp); if (pairInfo.blockTimestampLast == 0) { return (false, 0); } uint32 timeElapsed = blockTimestamp - pairInfo.blockTimestampLast; // overflow is desired if (timeElapsed < PERIOD) { return (true, pairInfo.priceAverage); } uint256 priceCumulative = _get(blockTimestamp); uint144 priceAverage = uint144(1e44 / uint256(FixedPoint .uq112x112(uint224((priceCumulative - pairInfo.priceCumulativeLast) / timeElapsed)) .mul(1e18) .decode144()).mul(uint256(FTM_USD.latestAnswer()))); return (true, priceAverage); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata) external view override returns (uint256 rate) { (uint256 reserve0, uint256 reserve1, ) = ICE_FTM.getReserves(); rate = 1e44 / (reserve0.mul(1e18) / reserve1).mul(uint256(FTM_USD.latestAnswer())); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "ICE TWAP"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "ICE"; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../interfaces/IOracle.sol"; // Chainlink Aggregator interface IAggregator { function latestAnswer() external view returns (int256 answer); } interface IWOHM { function sOHMTowOHM(uint256 _amount) external view returns (uint256); } contract wOHMOracle is IOracle { using BoringMath for uint256; // Keep everything in uint256 IAggregator public constant ohmOracle = IAggregator(0x90c2098473852E2F07678Fe1B6d595b1bd9b16Ed); IAggregator public constant ethUSDOracle = IAggregator(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); IWOHM public constant WOHM = IWOHM(0xCa76543Cf381ebBB277bE79574059e32108e3E65); // Calculates the lastest exchange rate // Uses both divide and multiply only for tokens not supported directly by Chainlink, for example MKR/USD function _get() internal view returns (uint256) { return 1e44 / (uint256(1e18).mul(uint256(ohmOracle.latestAnswer()).mul(uint256(ethUSDOracle.latestAnswer()))) / WOHM.sOHMTowOHM(1e9)); } // Get the latest exchange rate /// @inheritdoc IOracle function get(bytes calldata) public override returns (bool, uint256) { return (true, _get()); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata) public view override returns (bool, uint256) { return (true, _get()); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (, rate) = peek(data); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "wOHM Chainlink"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "LINK/wOHM"; } } // SPDX-License-Identifier: MIT import "../interfaces/IOracle.sol"; import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol"; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol"; /// @title ProxyOracle /// @author 0xMerlin /// @notice Oracle used for getting the price of an oracle implementation contract ProxyOracle is IOracle, BoringOwnable { IOracle public oracleImplementation; event LogOracleImplementationChange(IOracle indexed oldOracle, IOracle indexed newOracle); constructor() public {} function changeOracleImplementation(IOracle newOracle) external onlyOwner { IOracle oldOracle = oracleImplementation; oracleImplementation = newOracle; emit LogOracleImplementationChange(oldOracle, newOracle); } // Get the latest exchange rate /// @inheritdoc IOracle function get(bytes calldata data) public override returns (bool, uint256) { return oracleImplementation.get(data); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata data) public view override returns (bool, uint256) { return oracleImplementation.peek(data); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { return oracleImplementation.peekSpot(data); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "Proxy Oracle"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "Proxy"; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../interfaces/IOracle.sol"; /// @title PeggedOracle /// @author BoringCrypto /// @notice Oracle used for pegged prices that don't change /// @dev contract PeggedOracle is IOracle { /// @notice /// @dev /// @param rate (uint256) The fixed exchange rate /// @return (bytes) function getDataParameter(uint256 rate) public pure returns (bytes memory) { return abi.encode(rate); } // Get the exchange rate /// @inheritdoc IOracle function get(bytes calldata data) public override returns (bool, uint256) { uint256 rate = abi.decode(data, (uint256)); return (rate != 0, rate); } // Check the exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata data) public view override returns (bool, uint256) { uint256 rate = abi.decode(data, (uint256)); return (rate != 0, rate); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (, rate) = peek(data); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "Pegged"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "PEG"; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../interfaces/IOracle.sol"; import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; interface IAggregator { function latestAnswer() external view returns (int256 answer); } /// @title xSUSHIOracle /// @author BoringCrypto /// @notice Oracle used for getting the price of xSUSHI based on Chainlink /// @dev contract xSUSHIOracle is IOracle { using BoringMath for uint256; // Keep everything in uint256 IERC20 public immutable sushi; IERC20 public immutable bar; IAggregator public immutable sushiOracle; constructor( IERC20 sushi_, IERC20 bar_, IAggregator sushiOracle_ ) public { sushi = sushi_; bar = bar_; sushiOracle = sushiOracle_; } // Calculates the lastest exchange rate // Uses sushi rate and xSUSHI conversion and divide for any conversion other than from SUSHI to ETH function _get(address divide, uint256 decimals) internal view returns (uint256) { uint256 price = uint256(1e36); price = (price.mul(uint256(sushiOracle.latestAnswer())) / bar.totalSupply()).mul(sushi.balanceOf(address(bar))); if (divide != address(0)) { price = price / uint256(IAggregator(divide).latestAnswer()); } return price / decimals; } function getDataParameter(address divide, uint256 decimals) public pure returns (bytes memory) { return abi.encode(divide, decimals); } // Get the latest exchange rate /// @inheritdoc IOracle function get(bytes calldata data) public override returns (bool, uint256) { (address divide, uint256 decimals) = abi.decode(data, (address, uint256)); return (true, _get(divide, decimals)); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata data) public view override returns (bool, uint256) { (address divide, uint256 decimals) = abi.decode(data, (address, uint256)); return (true, _get(divide, decimals)); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (, rate) = peek(data); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "xSUSHI Chainlink"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "xSUSHI-LINK"; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../interfaces/IOracle.sol"; interface IUniswapAnchoredView { function price(string memory symbol) external view returns (uint256); } contract CompoundOracle is IOracle { using BoringMath for uint256; IUniswapAnchoredView private constant ORACLE = IUniswapAnchoredView(0x922018674c12a7F0D394ebEEf9B58F186CdE13c1); struct PriceInfo { uint128 price; uint128 blockNumber; } mapping(string => PriceInfo) public prices; function _peekPrice(string memory symbol) internal view returns (uint256) { if (bytes(symbol).length == 0) { return 1000000; } // To allow only using collateralSymbol or assetSymbol if paired against USDx PriceInfo memory info = prices[symbol]; if (block.number > info.blockNumber + 8) { return uint128(ORACLE.price(symbol)); // Prices are denominated with 6 decimals, so will fit in uint128 } return info.price; } function _getPrice(string memory symbol) internal returns (uint256) { if (bytes(symbol).length == 0) { return 1000000; } // To allow only using collateralSymbol or assetSymbol if paired against USDx PriceInfo memory info = prices[symbol]; if (block.number > info.blockNumber + 8) { info.price = uint128(ORACLE.price(symbol)); // Prices are denominated with 6 decimals, so will fit in uint128 info.blockNumber = uint128(block.number); // Blocknumber will fit in uint128 prices[symbol] = info; } return info.price; } function getDataParameter( string memory collateralSymbol, string memory assetSymbol, uint256 division ) public pure returns (bytes memory) { return abi.encode(collateralSymbol, assetSymbol, division); } // Get the latest exchange rate /// @inheritdoc IOracle function get(bytes calldata data) public override returns (bool, uint256) { (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); return (true, uint256(1e36).mul(_getPrice(assetSymbol)) / _getPrice(collateralSymbol) / division); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata data) public view override returns (bool, uint256) { (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); return (true, uint256(1e36).mul(_peekPrice(assetSymbol)) / _peekPrice(collateralSymbol) / division); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (, rate) = peek(data); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "Compound"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "COMP"; } } // SPDX-License-Identifier: MIT // Using the same Copyleft License as in the original Repository pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../interfaces/IOracle.sol"; contract CompositeOracle is IOracle { using BoringMath for uint256; function getDataParameter( IOracle oracle1, IOracle oracle2, bytes memory data1, bytes memory data2 ) public pure returns (bytes memory) { return abi.encode(oracle1, oracle2, data1, data2); } // Get the latest exchange rate, if no valid (recent) rate is available, return false /// @inheritdoc IOracle function get(bytes calldata data) external override returns (bool, uint256) { (IOracle oracle1, IOracle oracle2, bytes memory data1, bytes memory data2) = abi.decode(data, (IOracle, IOracle, bytes, bytes)); (bool success1, uint256 price1) = oracle1.get(data1); (bool success2, uint256 price2) = oracle2.get(data2); return (success1 && success2, price1.mul(price2) / 10**18); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata data) public view override returns (bool, uint256) { (IOracle oracle1, IOracle oracle2, bytes memory data1, bytes memory data2) = abi.decode(data, (IOracle, IOracle, bytes, bytes)); (bool success1, uint256 price1) = oracle1.peek(data1); (bool success2, uint256 price2) = oracle2.peek(data2); return (success1 && success2, price1.mul(price2) / 10**18); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (IOracle oracle1, IOracle oracle2, bytes memory data1, bytes memory data2) = abi.decode(data, (IOracle, IOracle, bytes, bytes)); uint256 price1 = oracle1.peekSpot(data1); uint256 price2 = oracle2.peekSpot(data2); return price1.mul(price2) / 10**18; } /// @inheritdoc IOracle function name(bytes calldata data) public view override returns (string memory) { (IOracle oracle1, IOracle oracle2, bytes memory data1, bytes memory data2) = abi.decode(data, (IOracle, IOracle, bytes, bytes)); return string(abi.encodePacked(oracle1.name(data1), "+", oracle2.name(data2))); } /// @inheritdoc IOracle function symbol(bytes calldata data) public view override returns (string memory) { (IOracle oracle1, IOracle oracle2, bytes memory data1, bytes memory data2) = abi.decode(data, (IOracle, IOracle, bytes, bytes)); return string(abi.encodePacked(oracle1.symbol(data1), "+", oracle2.symbol(data2))); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../interfaces/IOracle.sol"; // Chainlink Aggregator interface IAggregator { function latestAnswer() external view returns (int256 answer); } contract ChainlinkOracle is IOracle { using BoringMath for uint256; // Keep everything in uint256 // Calculates the lastest exchange rate // Uses both divide and multiply only for tokens not supported directly by Chainlink, for example MKR/USD function _get( address multiply, address divide, uint256 decimals ) internal view returns (uint256) { uint256 price = uint256(1e36); if (multiply != address(0)) { price = price.mul(uint256(IAggregator(multiply).latestAnswer())); } else { price = price.mul(1e18); } if (divide != address(0)) { price = price / uint256(IAggregator(divide).latestAnswer()); } return price / decimals; } function getDataParameter( address multiply, address divide, uint256 decimals ) public pure returns (bytes memory) { return abi.encode(multiply, divide, decimals); } // Get the latest exchange rate /// @inheritdoc IOracle function get(bytes calldata data) public override returns (bool, uint256) { (address multiply, address divide, uint256 decimals) = abi.decode(data, (address, address, uint256)); return (true, _get(multiply, divide, decimals)); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata data) public view override returns (bool, uint256) { (address multiply, address divide, uint256 decimals) = abi.decode(data, (address, address, uint256)); return (true, _get(multiply, divide, decimals)); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (, rate) = peek(data); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "Chainlink"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "LINK"; } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../interfaces/IOracle.sol"; // Band interface IStdReference { /// A structure returned whenever someone requests for standard reference data. struct ReferenceData { uint256 rate; // base/quote exchange rate, multiplied by 1e18. uint256 lastUpdatedBase; // UNIX epoch of the last time when base price gets updated. uint256 lastUpdatedQuote; // UNIX epoch of the last time when quote price gets updated. } /// Returns the price data for the given base/quote pair. Revert if not available. function getReferenceData(string memory _base, string memory _quote) external view returns (ReferenceData memory); /// Similar to getReferenceData, but with multiple base/quote pairs at once. function getReferenceDataBulk(string[] memory _bases, string[] memory _quotes) external view returns (ReferenceData[] memory); } contract BandOracleFTMV1 is IOracle { using BoringMath for uint256; // Keep everything in uint256 IStdReference constant ftmOracle = IStdReference(0x56E2898E0ceFF0D1222827759B56B28Ad812f92F); // Calculates the lastest exchange rate function _get() internal view returns (uint256 rate) { IStdReference.ReferenceData memory referenceData = ftmOracle.getReferenceData("USD", "FTM"); return referenceData.rate; } // Get the latest exchange rate /// @inheritdoc IOracle function get(bytes calldata) public override returns (bool, uint256) { return (true, _get()); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata) public view override returns (bool, uint256) { return (true, _get()); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (, rate) = peek(data); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "BAND FTM/USD"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "BAND"; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../interfaces/IOracle.sol"; // Chainlink Aggregator interface IAggregator { function latestAnswer() external view returns (int256 answer); } contract AVAXOracle is IOracle { using BoringMath for uint256; // Keep everything in uint256 IAggregator public constant avaxOracle = IAggregator(0x0A77230d17318075983913bC2145DB16C7366156); // Calculates the lastest exchange rate // Uses both divide and multiply only for tokens not supported directly by Chainlink, for example MKR/USD function _get() internal view returns (uint256) { return 1e26 / uint256(avaxOracle.latestAnswer()); } // Get the latest exchange rate /// @inheritdoc IOracle function get(bytes calldata) public override returns (bool, uint256) { return (true, _get()); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata) public view override returns (bool, uint256) { return (true, _get()); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (, rate) = peek(data); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "AVAX Chainlink"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "LINK/AVAX"; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../interfaces/IOracle.sol"; // Chainlink Aggregator interface IAggregator { function latestAnswer() external view returns (int256 answer); } contract ALCXOracle is IOracle { using BoringMath for uint256; // Keep everything in uint256 IAggregator public constant alcxOracle = IAggregator(0x194a9AaF2e0b67c35915cD01101585A33Fe25CAa); IAggregator public constant ethUSDOracle = IAggregator(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); // Calculates the lastest exchange rate // Uses both divide and multiply only for tokens not supported directly by Chainlink, for example MKR/USD function _get() internal view returns (uint256) { return 1e44 / uint256(alcxOracle.latestAnswer()).mul(uint256(ethUSDOracle.latestAnswer())); } // Get the latest exchange rate /// @inheritdoc IOracle function get(bytes calldata) public override returns (bool, uint256) { return (true, _get()); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata) public view override returns (bool, uint256) { return (true, _get()); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (, rate) = peek(data); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "ALCX Chainlink"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "LINK/ALCX"; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "../interfaces/IOracle.sol"; // WARNING: This oracle is only for testing, please use PeggedOracle for a fixed value oracle contract OracleMock is IOracle { using BoringMath for uint256; uint256 public rate; bool public success; constructor() public { success = true; } function set(uint256 rate_) public { // The rate can be updated. rate = rate_; } function setSuccess(bool val) public { success = val; } function getDataParameter() public pure returns (bytes memory) { return abi.encode("0x0"); } // Get the latest exchange rate function get(bytes calldata) public override returns (bool, uint256) { return (success, rate); } // Check the last exchange rate without any state changes function peek(bytes calldata) public view override returns (bool, uint256) { return (success, rate); } function peekSpot(bytes calldata) public view override returns (uint256) { return rate; } function name(bytes calldata) public view override returns (string memory) { return "Test"; } function symbol(bytes calldata) public view override returns (string memory) { return "TEST"; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol"; import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol"; import "./IOracle.sol"; import "./ISwapper.sol"; interface IKashiPair { event Approval(address indexed _owner, address indexed _spender, uint256 _value); event LogAccrue(uint256 accruedAmount, uint256 feeFraction, uint64 rate, uint256 utilization); event LogAddAsset(address indexed from, address indexed to, uint256 share, uint256 fraction); event LogAddCollateral(address indexed from, address indexed to, uint256 share); event LogBorrow(address indexed from, address indexed to, uint256 amount, uint256 part); event LogExchangeRate(uint256 rate); event LogFeeTo(address indexed newFeeTo); event LogRemoveAsset(address indexed from, address indexed to, uint256 share, uint256 fraction); event LogRemoveCollateral(address indexed from, address indexed to, uint256 share); event LogRepay(address indexed from, address indexed to, uint256 amount, uint256 part); event LogWithdrawFees(address indexed feeTo, uint256 feesEarnedFraction); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event Transfer(address indexed _from, address indexed _to, uint256 _value); function DOMAIN_SEPARATOR() external view returns (bytes32); function accrue() external; function accrueInfo() external view returns ( uint64 interestPerBlock, uint64 lastBlockAccrued, uint128 feesEarnedFraction ); function addAsset( address to, bool skim, uint256 share ) external returns (uint256 fraction); function addCollateral( address to, bool skim, uint256 share ) external; function allowance(address, address) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function asset() external view returns (IERC20); function balanceOf(address) external view returns (uint256); function bentoBox() external view returns (IBentoBoxV1); function borrow(address to, uint256 amount) external returns (uint256 part, uint256 share); function claimOwnership() external; function collateral() external view returns (IERC20); function cook( uint8[] calldata actions, uint256[] calldata values, bytes[] calldata datas ) external payable returns (uint256 value1, uint256 value2); function decimals() external view returns (uint8); function exchangeRate() external view returns (uint256); function feeTo() external view returns (address); function getInitData( IERC20 collateral_, IERC20 asset_, IOracle oracle_, bytes calldata oracleData_ ) external pure returns (bytes memory data); function init(bytes calldata data) external payable; function isSolvent(address user, bool open) external view returns (bool); function liquidate( address[] calldata users, uint256[] calldata borrowParts, address to, ISwapper swapper, bool open ) external; function masterContract() external view returns (address); function name() external view returns (string memory); function nonces(address) external view returns (uint256); function oracle() external view returns (IOracle); function oracleData() external view returns (bytes memory); function owner() external view returns (address); function pendingOwner() external view returns (address); function permit( address owner_, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function removeAsset(address to, uint256 fraction) external returns (uint256 share); function removeCollateral(address to, uint256 share) external; function repay( address to, bool skim, uint256 part ) external returns (uint256 amount); function setFeeTo(address newFeeTo) external; function setSwapper(ISwapper swapper, bool enable) external; function swappers(ISwapper) external view returns (bool); function symbol() external view returns (string memory); function totalAsset() external view returns (uint128 elastic, uint128 base); function totalBorrow() external view returns (uint128 elastic, uint128 base); function totalCollateralShare() external view returns (uint256); function totalSupply() external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function transferFrom( address from, address to, uint256 amount ) external returns (bool); function transferOwnership( address newOwner, bool direct, bool renounce ) external; function updateExchangeRate() external returns (bool updated, uint256 rate); function userBorrowPart(address) external view returns (uint256); function userCollateralShare(address) external view returns (uint256); function withdrawFees() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; contract ExternalFunctionMock { using BoringMath for uint256; event Result(uint256 output); function sum(uint256 a, uint256 b) external returns (uint256 c) { c = a.add(b); emit Result(c); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/ERC20.sol"; contract ERC20Mock is ERC20 { uint256 public override totalSupply; string public symbol; string public name; uint8 public decimals; constructor(uint256 _initialAmount) public { // Give the creator all initial tokens balanceOf[msg.sender] = _initialAmount; // Update total supply totalSupply = _initialAmount; } } //SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol"; // Modified from https://etherscan.io/address/0x6d903f6003cca6255d85cca4d3b5e5146dc33925#code and https://github.com/boringcrypto/dictator-dao/blob/main/contracts/DictatorDAO.sol#L225 contract MinimalTimeLock is BoringOwnable { event QueueTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data, uint256 eta); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data); uint256 public constant GRACE_PERIOD = 14 days; uint256 public constant DELAY = 2 days; mapping(bytes32 => uint256) public queuedTransactions; function queueTransaction( address target, uint256 value, bytes memory data ) public onlyOwner returns (bytes32) { bytes32 txHash = keccak256(abi.encode(target, value, data)); uint256 eta = block.timestamp + DELAY; queuedTransactions[txHash] = eta; emit QueueTransaction(txHash, target, value, data, eta); return txHash; } function cancelTransaction( address target, uint256 value, bytes memory data ) public onlyOwner { bytes32 txHash = keccak256(abi.encode(target, value, data)); queuedTransactions[txHash] = 0; emit CancelTransaction(txHash, target, value, data); } function executeTransaction( address target, uint256 value, bytes memory data ) public onlyOwner payable returns (bytes memory) { bytes32 txHash = keccak256(abi.encode(target, value, data)); uint256 eta = queuedTransactions[txHash]; require(block.timestamp >= eta, "Too early"); require(block.timestamp <= eta + GRACE_PERIOD, "Tx stale"); queuedTransactions[txHash] = 0; // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value: value}(data); require(success, "Tx reverted :("); emit ExecuteTransaction(txHash, target, value, data); return returnData; } }
Swaps to a flexible amount, from an exact input amount @inheritdoc ISwapper
function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom); uint256 amountFrom = YVIB.withdraw(); IronBank.remove_liquidity_one_coin(amountFrom, 2, 0, true); uint256 amountIntermediate = TETHER.balanceOf(address(this)); uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox)); (, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0); extraShare = shareReturned.sub(shareToMin); }
6,036,691
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY271() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF29(address account) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER864(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE821(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE56(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM782(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER882(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL38(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } function _MSGSENDER939() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function TOTALSUPPLY271() public view returns (uint) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF29(address account) public view returns (uint) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER864(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER3(_MSGSENDER939(), recipient, amount); return true; } function ALLOWANCE821(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE56(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE188(_MSGSENDER939(), spender, amount); return true; } function TRANSFERFROM782(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER3(sender, recipient, amount); _APPROVE188(sender, _MSGSENDER939(), _allowances[sender][_MSGSENDER939()].SUB987(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE479(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE188(_MSGSENDER939(), spender, _allowances[_MSGSENDER939()][spender].ADD671(addedValue)); return true; } function DECREASEALLOWANCE547(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE188(_MSGSENDER939(), spender, _allowances[_MSGSENDER939()][spender].SUB987(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER3(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB987(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD671(amount); emit TRANSFER882(sender, recipient, amount); } function _MINT404(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD671(amount); _balances[account] = _balances[account].ADD671(amount); emit TRANSFER882(address(0), account, amount); } function _BURN359(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB987(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB987(amount); emit TRANSFER882(account, address(0), amount); } function _APPROVE188(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL38(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME730() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL333() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS459() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } library SafeMath { function ADD671(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB987(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return SUB987(a, b, "SafeMath: subtraction overflow"); } function SUB987(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint c = a - b; return c; } function MUL833(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV482(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return DIV482(a, b, "SafeMath: division by zero"); } function DIV482(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function ISCONTRACT215(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function SAFETRANSFER802(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN834(token, abi.encodeWithSelector(token.TRANSFER864.selector, to, value)); } function SAFETRANSFERFROM543(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN834(token, abi.encodeWithSelector(token.TRANSFERFROM782.selector, from, to, value)); } function SAFEAPPROVE220(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE821(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN834(token, abi.encodeWithSelector(token.APPROVE56.selector, spender, value)); } function CALLOPTIONALRETURN834(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT215(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract OnitContract is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; mapping (address => bool) public minters; uint256 private _initSeedRound = 150; constructor () public ERC20Detailed("onbuff.io", "ONIT", 0) { governance = msg.sender; _MINT404(governance,_initSeedRound*10**uint(DECIMALS459())); } function MINT706(address account, uint amount) public { //inject NONSTANDARD NAMING require(minters[msg.sender], "!minter"); _MINT404(account, amount); } function SETGOVERNANCE359(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function ADDMINTER824(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = true; } function REMOVEMINTER93(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = false; } }
inject NONSTANDARD NAMING
function _APPROVE188(address owner, address spender, uint amount) internal {
12,602,582
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&&BBBBBBBGG&@@@@@@@@@&&&&&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&P!: :[email protected]@@@&P7^. .^?G&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@&J. :#@@@#7. :Y&@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@&! [email protected]@@B: !&@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@P [email protected]@@~ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@J [email protected]@&. [email protected]@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@G [email protected]@@. [email protected]@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@. &@@Y #@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@& [email protected]@@&##########&&&&&&&&&&&#############@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@& [email protected]@@@@@@@@@@@@@#B######&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@. &@@@@@@@@@@@@@B~ .:!5&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@B [email protected]@@@@@@@@@@@@@@&! .7#@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@Y [email protected]@@@@@@@@@@@@@@@B. ^#@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@G [email protected]@@@@@@@@@@@@@@@@: [email protected]@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@? [email protected]@@@@@@@@@@@@@@@@. ^@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@5: [email protected]@@@@@@@@@@@@@@B [email protected]@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&G7^. :[email protected]@@@@@@@@@@@@@: #@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&#######BB&@@@@@@@@@@@@@7 [email protected]@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@? [email protected]@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@. ^@@@: [email protected]@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@Y [email protected]@# ^@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@! [email protected]@@: [email protected]@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@Y [email protected]@@^ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@&~ !&@@&. :[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@&?. .J&@@@? [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#Y~. :!5&@@@#7 .^[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&#BGGGB#&@@@@@@@@BPGGGGGGB#&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721RoyaltyUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@imtbl/imx-contracts/contracts/IMintable.sol"; import "@imtbl/imx-contracts/contracts/utils/Minting.sol"; import "./interfaces/IExtensionManager.sol"; contract StoryversePlot is Initializable, ERC721RoyaltyUpgradeable, ERC721BurnableUpgradeable, AccessControlUpgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable, IMintable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // token state variables string public baseURI; uint256 public totalSupply; IExtensionManager public extensionManager; address public imx; mapping(uint256 => bytes) public blueprints; // ------------------ keep state variables above this line ------------------ /// @notice Emitted when a new extension manager is set /// @param who Admin that set the extension manager /// @param extensionManager New extension manager contract event ExtensionManagerSet(address indexed who, address indexed extensionManager); /// @notice Emitted when a new Immutable X is set /// @param who Admin that set the extension manager /// @param imx New Immutable X address event IMXSet(address indexed who, address indexed imx); /// @notice Emitted when a new token is minted and a blueprint is set /// @param to Owner of the newly minted token /// @param tokenId Token ID that was minted /// @param blueprint Blueprint extracted from the blob event AssetMinted(address to, uint256 tokenId, bytes blueprint); /// @notice Emitted when the new base URI is set /// @param who Admin that set the base URI event BaseURISet(address indexed who); /// @notice Emitted when funds are withdrawn from the contract /// @param to Recipient of the funds /// @param amount Amount sent in Wei event FundsWithdrawn(address to, uint256 amount); /// @notice Checks if the extension manager is set modifier extensionManagerSet() { if (isExtensionManagerSet()) { _; } } /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} /// @notice Initializes the contract /// @param _uri Base URI function initialize(string calldata _uri) public initializer { __ERC721_init("Storyverse Plot", "PLOT"); __AccessControl_init(); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(MINTER_ROLE, msg.sender); _transferOwnership(msg.sender); baseURI = _uri; emit BaseURISet(msg.sender); } /// @notice Checks if the extension manager is set /// @return true if the extension manager is set to non-zero address function isExtensionManagerSet() internal view returns (bool) { return address(extensionManager) != address(0); } /// @notice Sets a new extension manager /// @param _extensionManager New extension manager function setExtensionManager(address _extensionManager) public onlyRole(DEFAULT_ADMIN_ROLE) { require( _extensionManager == address(0) || IERC165Upgradeable(_extensionManager).supportsInterface( type(IExtensionManager).interfaceId ), "invalid extension manager" ); extensionManager = IExtensionManager(_extensionManager); emit ExtensionManagerSet(msg.sender, _extensionManager); } /// @notice Mint a new token /// @param _to Owner of the newly minted token /// @param _tokenId Token ID function safeMint(address _to, uint256 _tokenId) public onlyRole(MINTER_ROLE) { _safeMint(_to, _tokenId); } /// @notice Grants approval to an address for a token ID /// @param _to Delegate who will be able to transfer the token on behalf of the owner /// @param _tokenId Token ID function approve(address _to, uint256 _tokenId) public override { if (isExtensionManagerSet()) { extensionManager.beforeTokenApprove(_to, _tokenId); } super.approve(_to, _tokenId); if (isExtensionManagerSet()) { extensionManager.afterTokenApprove(_to, _tokenId); } } /// @notice Approves or disapproves for all the tokens owned by an address /// @param _operator Delegate who will be able to transfer all tokens on behalf of the owner /// @param _approved Whether to grant or revoke approval function setApprovalForAll(address _operator, bool _approved) public override { if (isExtensionManagerSet()) { extensionManager.beforeApproveAll(_operator, _approved); } super.setApprovalForAll(_operator, _approved); if (isExtensionManagerSet()) { extensionManager.afterApproveAll(_operator, _approved); } } function _beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) internal virtual override { if (isExtensionManagerSet()) { extensionManager.beforeTokenTransfer(_from, _to, _tokenId); } super._beforeTokenTransfer(_from, _to, _tokenId); if (_from == address(0)) { totalSupply++; } if (_to == address(0)) { totalSupply--; } } function _afterTokenTransfer( address _from, address _to, uint256 _tokenId ) internal virtual override { if (isExtensionManagerSet()) { extensionManager.afterTokenTransfer(_from, _to, _tokenId); } super._afterTokenTransfer(_from, _to, _tokenId); } /// @notice Sets a base URI /// @param _uri Base URI function setBaseURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { baseURI = _uri; emit BaseURISet(msg.sender); } function _baseURI() internal view override returns (string memory) { return baseURI; } /// @notice Get a token's URI /// @param _tokenId Token ID /// @return uri_ URI of the token function tokenURI(uint256 _tokenId) public view override returns (string memory uri_) { if (isExtensionManagerSet()) { return extensionManager.tokenURI(_tokenId); } return super.tokenURI(_tokenId); } /// @notice Get the royalty information of the token, conforms to the EIP-2981 specification /// @param _tokenId Token ID /// @param _salePrice Sale price of the token /// @return receiver_ Receiver of the royalty /// @return royaltyAmount_ Royalty amount function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override extensionManagerSet returns (address receiver_, uint256 royaltyAmount_) { return extensionManager.royaltyInfo(_tokenId, _salePrice); } /// @notice Get PLOT data for the token ID /// @param _tokenId Token ID /// @param _in Input data /// @return out_ Output data function getPLOTData(uint256 _tokenId, bytes memory _in) public view extensionManagerSet returns (bytes memory out_) { return extensionManager.getPLOTData(_tokenId, _in); } /// @notice Sets PLOT data for the token ID /// @param _tokenId Token ID /// @param _in Input data /// @return out_ Output data function setPLOTData(uint256 _tokenId, bytes memory _in) public extensionManagerSet returns (bytes memory out_) { return extensionManager.setPLOTData(_tokenId, _in); } /// @notice Pays for PLOT data of the token ID /// @param _tokenId Token ID /// @param _in Input data /// @return out_ Output data function payPLOTData(uint256 _tokenId, bytes memory _in) public payable extensionManagerSet returns (bytes memory out_) { bool ok; (ok, out_) = payable(address(extensionManager)).call{value: msg.value}( abi.encodeCall(extensionManager.payPLOTData, (_tokenId, _in)) ); require(ok, "payment failed"); return out_; } /// @notice Get data /// @param _in Input data /// @return out_ Output data function getData(bytes memory _in) public view extensionManagerSet returns (bytes memory out_) { return extensionManager.getData(_in); } /// @notice Sets data /// @param _in Input data /// @return out_ Output data function setData(bytes memory _in) public extensionManagerSet returns (bytes memory out_) { return extensionManager.setData(_in); } /// @notice Pays for data /// @param _in Input data /// @return out_ Output data function payData(bytes memory _in) public payable extensionManagerSet returns (bytes memory out_) { bool ok; (ok, out_) = payable(address(extensionManager)).call{value: msg.value}( abi.encodeCall(extensionManager.payData, _in) ); require(ok, "payment failed"); return out_; } /// @notice Transfers the ownership of the contract /// @param newOwner New owner of the contract function transferOwnership(address newOwner) public virtual override onlyRole(DEFAULT_ADMIN_ROLE) { require(newOwner != address(0), "new owner is the zero address"); _transferOwnership(newOwner); } /// @notice Sets the Immutable X address /// @param _imx New Immutable X function setIMX(address _imx) external onlyRole(DEFAULT_ADMIN_ROLE) { imx = _imx; emit IMXSet(msg.sender, imx); } /// @notice Mints a new token from a blob /// @param _to Owner of the newly minted token /// @param _quantity Token quantity, only 1 is supported /// @param _mintingBlob Blob of the format {token_id}:{blueprint} function mintFor( address _to, uint256 _quantity, bytes calldata _mintingBlob ) external { require( hasRole(MINTER_ROLE, msg.sender) || msg.sender == imx, "function can only be called by owner or IMX" ); require(_quantity == 1, "Mintable: invalid quantity"); (uint256 tokenId, bytes memory blueprint) = Minting.split(_mintingBlob); _safeMint(_to, tokenId); blueprints[tokenId] = blueprint; emit AssetMinted(_to, tokenId, blueprint); } /// @notice Withdraw funds from the contract /// @param _to Recipient of the funds /// @param _amount Amount sent, in Wei function withdrawFunds(address payable _to, uint256 _amount) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant { require(_amount <= address(this).balance, "not enough funds"); _to.transfer(_amount); emit FundsWithdrawn(_to, _amount); } // The following functions are overrides required by Solidity. function supportsInterface(bytes4 interfaceId) public view override(ERC721RoyaltyUpgradeable, ERC721Upgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function _burn(uint256 _tokenId) internal override(ERC721RoyaltyUpgradeable, ERC721Upgradeable) { super._burn(_tokenId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/ERC721Royalty.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../common/ERC2981Upgradeable.sol"; import "../../../utils/introspection/ERC165Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Extension of ERC721 with the ERC2981 NFT Royalty Standard, a standardized way to retrieve royalty payment * information. * * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. * * _Available since v4.5._ */ abstract contract ERC721RoyaltyUpgradeable is Initializable, ERC2981Upgradeable, ERC721Upgradeable { function __ERC721Royalty_init() internal onlyInitializing { } function __ERC721Royalty_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, ERC2981Upgradeable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev See {ERC721-_burn}. This override additionally clears the royalty information for the token. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); _resetTokenRoyalty(tokenId); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal onlyInitializing { } function __ERC721Burnable_init_unchained() internal onlyInitializing { } /** * @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); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } 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(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _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 This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ 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() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // 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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IMintable { function mintFor( address to, uint256 quantity, bytes calldata mintingBlob ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./Bytes.sol"; library Minting { // Split the minting blob into token_id and blueprint portions // {token_id}:{blueprint} function split(bytes calldata blob) internal pure returns (uint256, bytes memory) { int256 index = Bytes.indexOf(blob, ":", 0); require(index >= 0, "Separator must exist"); // Trim the { and } from the parameters uint256 tokenID = Bytes.toUint(blob[1:uint256(index) - 1]); uint256 blueprintLength = blob.length - uint256(index) - 3; if (blueprintLength == 0) { return (tokenID, bytes("")); } bytes calldata blueprint = blob[uint256(index) + 2:blob.length - 1]; return (tokenID, blueprint); } } // SPDX-License-Identifier: Unlicensed pragma solidity ~0.8.13; interface IExtensionManager { function beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) external; function afterTokenTransfer( address _from, address _to, uint256 _tokenId ) external; function beforeTokenApprove(address _to, uint256 _tokenId) external; function afterTokenApprove(address _to, uint256 _tokenId) external; function beforeApproveAll(address _operator, bool _approved) external; function afterApproveAll(address _operator, bool _approved) external; function tokenURI(uint256 _tokenId) external view returns (string memory uri_); function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address royaltyReceiver_, uint256 royaltyAmount_); function getPLOTData(uint256 _tokenId, bytes memory _in) external view returns (bytes memory out_); function setPLOTData(uint256 _tokenId, bytes memory _in) external returns (bytes memory out_); function payPLOTData(uint256 _tokenId, bytes memory _in) external payable returns (bytes memory out_); function getData(bytes memory _in) external view returns (bytes memory out_); function setData(bytes memory _in) external returns (bytes memory out_); function payData(bytes memory _in) external payable returns (bytes memory out_); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/common/ERC2981.sol) pragma solidity ^0.8.0; import "../../interfaces/IERC2981Upgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. * * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the * fee is specified in basis points by default. * * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. * * _Available since v4.5._ */ abstract contract ERC2981Upgradeable is Initializable, IERC2981Upgradeable, ERC165Upgradeable { function __ERC2981_init() internal onlyInitializing { } function __ERC2981_init_unchained() internal onlyInitializing { } struct RoyaltyInfo { address receiver; uint96 royaltyFraction; } RoyaltyInfo private _defaultRoyaltyInfo; mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC165Upgradeable) returns (bool) { return interfaceId == type(IERC2981Upgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @inheritdoc IERC2981Upgradeable */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view virtual override returns (address, uint256) { RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; if (royalty.receiver == address(0)) { royalty = _defaultRoyaltyInfo; } uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); return (royalty.receiver, royaltyAmount); } /** * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an * override. */ function _feeDenominator() internal pure virtual returns (uint96) { return 10000; } /** * @dev Sets the royalty information that all ids in this contract will default to. * * Requirements: * * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: invalid receiver"); _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Removes default royalty information. */ function _deleteDefaultRoyalty() internal virtual { delete _defaultRoyaltyInfo; } /** * @dev Sets the royalty information for a specific token id, overriding the global default. * * Requirements: * * - `tokenId` must be already minted. * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setTokenRoyalty( uint256 tokenId, address receiver, uint96 feeNumerator ) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: Invalid parameters"); _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Resets royalty information for the token id back to the global default. */ function _resetTokenRoyalty(uint256 tokenId) internal virtual { delete _tokenRoyaltyInfo[tokenId]; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[48] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // 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 IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library 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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev 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; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981Upgradeable is IERC165Upgradeable { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @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.4; library Bytes { /** * @dev Converts a `uint256` to a `string`. * via OraclizeAPI - MIT licence * https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol */ function fromUint(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } bytes constant alphabet = "0123456789abcdef"; /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf( bytes memory _base, string memory _value, uint256 _offset ) internal pure returns (int256) { bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for (uint256 i = _offset; i < _base.length; i++) { if (_base[i] == _valueBytes[0]) { return int256(i); } } return -1; } function substring( bytes memory strBytes, uint256 startIndex, uint256 endIndex ) internal pure returns (string memory) { bytes memory result = new bytes(endIndex - startIndex); for (uint256 i = startIndex; i < endIndex; i++) { result[i - startIndex] = strBytes[i]; } return string(result); } function toUint(bytes memory b) internal pure returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < b.length; i++) { uint256 val = uint256(uint8(b[i])); if (val >= 48 && val <= 57) { // input is 0-9 result = result * 10 + (val - 48); } else { // invalid character, expecting integer input revert("invalid input, only numbers allowed"); } } return result; } }
Grants approval to an address for a token ID _to Delegate who will be able to transfer the token on behalf of the owner _tokenId Token ID
function approve(address _to, uint256 _tokenId) public override { if (isExtensionManagerSet()) { extensionManager.beforeTokenApprove(_to, _tokenId); } super.approve(_to, _tokenId); if (isExtensionManagerSet()) { extensionManager.afterTokenApprove(_to, _tokenId); } }
6,953,061
./full_match/4/0x0D3152f4f3dd9144Cfc611396A5277D52F6d0422/sources/pixelSlime_flat.sol
add an address to the whitelist addr address return true if the address was added to the whitelist, false if the address was already in the whitelist/
function addAddressToWhitelist(address addr) public onlyOwner returns (bool){ if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); return true; } return false; }
653,180
// File: contracts/IManager.sol pragma solidity ^0.5.11; contract IManager { event SetController(address controller); event ParameterUpdate(string param); function setController(address _controller) external; } // File: contracts/zeppelin/Ownable.sol pragma solidity ^0.5.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. */ 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 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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/zeppelin/Pausable.sol pragma solidity ^0.5.11; /** * @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() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: contracts/IController.sol pragma solidity ^0.5.11; contract IController is Pausable { event SetContractInfo(bytes32 id, address contractAddress, bytes20 gitCommitHash); function setContractInfo(bytes32 _id, address _contractAddress, bytes20 _gitCommitHash) external; function updateController(bytes32 _id, address _controller) external; function getContract(bytes32 _id) public view returns (address); } // File: contracts/Manager.sol pragma solidity ^0.5.11; contract Manager is IManager { // Controller that contract is registered with IController public controller; // Check if sender is controller modifier onlyController() { require(msg.sender == address(controller), "caller must be Controller"); _; } // Check if sender is controller owner modifier onlyControllerOwner() { require(msg.sender == controller.owner(), "caller must be Controller owner"); _; } // Check if controller is not paused modifier whenSystemNotPaused() { require(!controller.paused(), "system is paused"); _; } // Check if controller is paused modifier whenSystemPaused() { require(controller.paused(), "system is not paused"); _; } constructor(address _controller) public { controller = IController(_controller); } /** * @notice Set controller. Only callable by current controller * @param _controller Controller contract address */ function setController(address _controller) external onlyController { controller = IController(_controller); emit SetController(_controller); } } // File: contracts/ManagerProxyTarget.sol pragma solidity ^0.5.11; /** * @title ManagerProxyTarget * @notice The base contract that target contracts used by a proxy contract should inherit from * @dev Both the target contract and the proxy contract (implemented as ManagerProxy) MUST inherit from ManagerProxyTarget in order to guarantee that both contracts have the same storage layout. Differing storage layouts in a proxy contract and target contract can potentially break the delegate proxy upgradeability mechanism */ contract ManagerProxyTarget is Manager { // Used to look up target contract address in controller's registry bytes32 public targetContractId; } // File: contracts/bonding/IBondingManager.sol pragma solidity ^0.5.11; /** * @title Interface for BondingManager * TODO: switch to interface type */ contract IBondingManager { event TranscoderUpdate(address indexed transcoder, uint256 rewardCut, uint256 feeShare); event TranscoderActivated(address indexed transcoder, uint256 activationRound); event TranscoderDeactivated(address indexed transcoder, uint256 deactivationRound); event TranscoderSlashed(address indexed transcoder, address finder, uint256 penalty, uint256 finderReward); event Reward(address indexed transcoder, uint256 amount); event Bond(address indexed newDelegate, address indexed oldDelegate, address indexed delegator, uint256 additionalAmount, uint256 bondedAmount); event Unbond(address indexed delegate, address indexed delegator, uint256 unbondingLockId, uint256 amount, uint256 withdrawRound); event Rebond(address indexed delegate, address indexed delegator, uint256 unbondingLockId, uint256 amount); event WithdrawStake(address indexed delegator, uint256 unbondingLockId, uint256 amount, uint256 withdrawRound); event WithdrawFees(address indexed delegator); event EarningsClaimed(address indexed delegate, address indexed delegator, uint256 rewards, uint256 fees, uint256 startRound, uint256 endRound); // Deprecated events // These event signatures can be used to construct the appropriate topic hashes to filter for past logs corresponding // to these deprecated events. // event Bond(address indexed delegate, address indexed delegator); // event Unbond(address indexed delegate, address indexed delegator); // event WithdrawStake(address indexed delegator); // event TranscoderUpdate(address indexed transcoder, uint256 pendingRewardCut, uint256 pendingFeeShare, uint256 pendingPricePerSegment, bool registered); // event TranscoderEvicted(address indexed transcoder); // event TranscoderResigned(address indexed transcoder); // External functions function updateTranscoderWithFees(address _transcoder, uint256 _fees, uint256 _round) external; function slashTranscoder(address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee) external; function setCurrentRoundTotalActiveStake() external; // Public functions function getTranscoderPoolSize() public view returns (uint256); function transcoderTotalStake(address _transcoder) public view returns (uint256); function isActiveTranscoder(address _transcoder) public view returns (bool); function getTotalBonded() public view returns (uint256); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts/libraries/SortedDoublyLL.sol pragma solidity ^0.5.11; /** * @title A sorted doubly linked list with nodes sorted in descending order. Optionally accepts insert position hints * * Given a new node with a `key`, a hint is of the form `(prevId, nextId)` s.t. `prevId` and `nextId` are adjacent in the list. * `prevId` is a node with a key >= `key` and `nextId` is a node with a key <= `key`. If the sender provides a hint that is a valid insert position * the insert operation is a constant time storage write. However, the provided hint in a given transaction might be a valid insert position, but if other transactions are included first, when * the given transaction is executed the provided hint may no longer be a valid insert position. For example, one of the nodes referenced might be removed or their keys may * be updated such that the the pair of nodes in the hint no longer represent a valid insert position. If one of the nodes in the hint becomes invalid, we still try to use the other * valid node as a starting point for finding the appropriate insert position. If both nodes in the hint become invalid, we use the head of the list as a starting point * to find the appropriate insert position. */ library SortedDoublyLL { using SafeMath for uint256; // Information for a node in the list struct Node { uint256 key; // Node's key used for sorting address nextId; // Id of next node (smaller key) in the list address prevId; // Id of previous node (larger key) in the list } // Information for the list struct Data { address head; // Head of the list. Also the node in the list with the largest key address tail; // Tail of the list. Also the node in the list with the smallest key uint256 maxSize; // Maximum size of the list uint256 size; // Current size of the list mapping (address => Node) nodes; // Track the corresponding ids for each node in the list } /** * @dev Set the maximum size of the list * @param _size Maximum size */ function setMaxSize(Data storage self, uint256 _size) public { require(_size > self.maxSize, "new max size must be greater than old max size"); self.maxSize = _size; } /** * @dev Add a node to the list * @param _id Node's id * @param _key Node's key * @param _prevId Id of previous node for the insert position * @param _nextId Id of next node for the insert position */ function insert(Data storage self, address _id, uint256 _key, address _prevId, address _nextId) public { // List must not be full require(!isFull(self), "list is full"); // List must not already contain node require(!contains(self, _id), "node already in list"); // Node id must not be null require(_id != address(0), "node id is null"); // Key must be non-zero require(_key > 0, "key is zero"); address prevId = _prevId; address nextId = _nextId; if (!validInsertPosition(self, _key, prevId, nextId)) { // Sender's hint was not a valid insert position // Use sender's hint to find a valid insert position (prevId, nextId) = findInsertPosition(self, _key, prevId, nextId); } self.nodes[_id].key = _key; if (prevId == address(0) && nextId == address(0)) { // Insert as head and tail self.head = _id; self.tail = _id; } else if (prevId == address(0)) { // Insert before `prevId` as the head self.nodes[_id].nextId = self.head; self.nodes[self.head].prevId = _id; self.head = _id; } else if (nextId == address(0)) { // Insert after `nextId` as the tail self.nodes[_id].prevId = self.tail; self.nodes[self.tail].nextId = _id; self.tail = _id; } else { // Insert at insert position between `prevId` and `nextId` self.nodes[_id].nextId = nextId; self.nodes[_id].prevId = prevId; self.nodes[prevId].nextId = _id; self.nodes[nextId].prevId = _id; } self.size = self.size.add(1); } /** * @dev Remove a node from the list * @param _id Node's id */ function remove(Data storage self, address _id) public { // List must contain the node require(contains(self, _id), "node not in list"); if (self.size > 1) { // List contains more than a single node if (_id == self.head) { // The removed node is the head // Set head to next node self.head = self.nodes[_id].nextId; // Set prev pointer of new head to null self.nodes[self.head].prevId = address(0); } else if (_id == self.tail) { // The removed node is the tail // Set tail to previous node self.tail = self.nodes[_id].prevId; // Set next pointer of new tail to null self.nodes[self.tail].nextId = address(0); } else { // The removed node is neither the head nor the tail // Set next pointer of previous node to the next node self.nodes[self.nodes[_id].prevId].nextId = self.nodes[_id].nextId; // Set prev pointer of next node to the previous node self.nodes[self.nodes[_id].nextId].prevId = self.nodes[_id].prevId; } } else { // List contains a single node // Set the head and tail to null self.head = address(0); self.tail = address(0); } delete self.nodes[_id]; self.size = self.size.sub(1); } /** * @dev Update the key of a node in the list * @param _id Node's id * @param _newKey Node's new key * @param _prevId Id of previous node for the new insert position * @param _nextId Id of next node for the new insert position */ function updateKey(Data storage self, address _id, uint256 _newKey, address _prevId, address _nextId) public { // List must contain the node require(contains(self, _id), "node not in list"); // Remove node from the list remove(self, _id); if (_newKey > 0) { // Insert node if it has a non-zero key insert(self, _id, _newKey, _prevId, _nextId); } } /** * @dev Checks if the list contains a node * @param _id Address of transcoder * @return true if '_id' is in list */ function contains(Data storage self, address _id) public view returns (bool) { // List only contains non-zero keys, so if key is non-zero the node exists return self.nodes[_id].key > 0; } /** * @dev Checks if the list is full * @return true if list is full */ function isFull(Data storage self) public view returns (bool) { return self.size == self.maxSize; } /** * @dev Checks if the list is empty * @return true if list is empty */ function isEmpty(Data storage self) public view returns (bool) { return self.size == 0; } /** * @dev Returns the current size of the list * @return current size of the list */ function getSize(Data storage self) public view returns (uint256) { return self.size; } /** * @dev Returns the maximum size of the list */ function getMaxSize(Data storage self) public view returns (uint256) { return self.maxSize; } /** * @dev Returns the key of a node in the list * @param _id Node's id * @return key for node with '_id' */ function getKey(Data storage self, address _id) public view returns (uint256) { return self.nodes[_id].key; } /** * @dev Returns the first node in the list (node with the largest key) * @return address for the head of the list */ function getFirst(Data storage self) public view returns (address) { return self.head; } /** * @dev Returns the last node in the list (node with the smallest key) * @return address for the tail of the list */ function getLast(Data storage self) public view returns (address) { return self.tail; } /** * @dev Returns the next node (with a smaller key) in the list for a given node * @param _id Node's id * @return address for the node following node in list with '_id' */ function getNext(Data storage self, address _id) public view returns (address) { return self.nodes[_id].nextId; } /** * @dev Returns the previous node (with a larger key) in the list for a given node * @param _id Node's id * address for the node before node in list with '_id' */ function getPrev(Data storage self, address _id) public view returns (address) { return self.nodes[_id].prevId; } /** * @dev Check if a pair of nodes is a valid insertion point for a new node with the given key * @param _key Node's key * @param _prevId Id of previous node for the insert position * @param _nextId Id of next node for the insert position * @return if the insert position is valid */ function validInsertPosition(Data storage self, uint256 _key, address _prevId, address _nextId) public view returns (bool) { if (_prevId == address(0) && _nextId == address(0)) { // `(null, null)` is a valid insert position if the list is empty return isEmpty(self); } else if (_prevId == address(0)) { // `(null, _nextId)` is a valid insert position if `_nextId` is the head of the list return self.head == _nextId && _key >= self.nodes[_nextId].key; } else if (_nextId == address(0)) { // `(_prevId, null)` is a valid insert position if `_prevId` is the tail of the list return self.tail == _prevId && _key <= self.nodes[_prevId].key; } else { // `(_prevId, _nextId)` is a valid insert position if they are adjacent nodes and `_key` falls between the two nodes' keys return self.nodes[_prevId].nextId == _nextId && self.nodes[_prevId].key >= _key && _key >= self.nodes[_nextId].key; } } /** * @dev Descend the list (larger keys to smaller keys) to find a valid insert position * @param _key Node's key * @param _startId Id of node to start ascending the list from */ function descendList(Data storage self, uint256 _key, address _startId) private view returns (address, address) { // If `_startId` is the head, check if the insert position is before the head if (self.head == _startId && _key >= self.nodes[_startId].key) { return (address(0), _startId); } address prevId = _startId; address nextId = self.nodes[prevId].nextId; // Descend the list until we reach the end or until we find a valid insert position while (prevId != address(0) && !validInsertPosition(self, _key, prevId, nextId)) { prevId = self.nodes[prevId].nextId; nextId = self.nodes[prevId].nextId; } return (prevId, nextId); } /** * @dev Ascend the list (smaller keys to larger keys) to find a valid insert position * @param _key Node's key * @param _startId Id of node to start descending the list from */ function ascendList(Data storage self, uint256 _key, address _startId) private view returns (address, address) { // If `_startId` is the tail, check if the insert position is after the tail if (self.tail == _startId && _key <= self.nodes[_startId].key) { return (_startId, address(0)); } address nextId = _startId; address prevId = self.nodes[nextId].prevId; // Ascend the list until we reach the end or until we find a valid insertion point while (nextId != address(0) && !validInsertPosition(self, _key, prevId, nextId)) { nextId = self.nodes[nextId].prevId; prevId = self.nodes[nextId].prevId; } return (prevId, nextId); } /** * @dev Find the insert position for a new node with the given key * @param _key Node's key * @param _prevId Id of previous node for the insert position * @param _nextId Id of next node for the insert position */ function findInsertPosition(Data storage self, uint256 _key, address _prevId, address _nextId) private view returns (address, address) { address prevId = _prevId; address nextId = _nextId; if (prevId != address(0)) { if (!contains(self, prevId) || _key > self.nodes[prevId].key) { // `prevId` does not exist anymore or now has a smaller key than the given key prevId = address(0); } } if (nextId != address(0)) { if (!contains(self, nextId) || _key < self.nodes[nextId].key) { // `nextId` does not exist anymore or now has a larger key than the given key nextId = address(0); } } if (prevId == address(0) && nextId == address(0)) { // No hint - descend list starting from head return descendList(self, _key, self.head); } else if (prevId == address(0)) { // No `prevId` for hint - ascend list starting from `nextId` return ascendList(self, _key, nextId); } else if (nextId == address(0)) { // No `nextId` for hint - descend list starting from `prevId` return descendList(self, _key, prevId); } else { // Descend list starting from `prevId` return descendList(self, _key, prevId); } } } // File: contracts/libraries/MathUtils.sol pragma solidity ^0.5.11; library MathUtils { using SafeMath for uint256; // Divisor used for representing percentages uint256 public constant PERC_DIVISOR = 1000000; /** * @dev Returns whether an amount is a valid percentage out of PERC_DIVISOR * @param _amount Amount that is supposed to be a percentage */ function validPerc(uint256 _amount) internal pure returns (bool) { return _amount <= PERC_DIVISOR; } /** * @dev Compute percentage of a value with the percentage represented by a fraction * @param _amount Amount to take the percentage of * @param _fracNum Numerator of fraction representing the percentage * @param _fracDenom Denominator of fraction representing the percentage */ function percOf(uint256 _amount, uint256 _fracNum, uint256 _fracDenom) internal pure returns (uint256) { return _amount.mul(percPoints(_fracNum, _fracDenom)).div(PERC_DIVISOR); } /** * @dev Compute percentage of a value with the percentage represented by a fraction over PERC_DIVISOR * @param _amount Amount to take the percentage of * @param _fracNum Numerator of fraction representing the percentage with PERC_DIVISOR as the denominator */ function percOf(uint256 _amount, uint256 _fracNum) internal pure returns (uint256) { return _amount.mul(_fracNum).div(PERC_DIVISOR); } /** * @dev Compute percentage representation of a fraction * @param _fracNum Numerator of fraction represeting the percentage * @param _fracDenom Denominator of fraction represeting the percentage */ function percPoints(uint256 _fracNum, uint256 _fracDenom) internal pure returns (uint256) { return _fracNum.mul(PERC_DIVISOR).div(_fracDenom); } } // File: contracts/bonding/libraries/EarningsPool.sol pragma solidity ^0.5.11; /** * @title EarningsPool * @dev Manages reward and fee pools for delegators and transcoders */ library EarningsPool { using SafeMath for uint256; // Represents rewards and fees to be distributed to delegators // The `hasTranscoderRewardFeePool` flag was introduced so that EarningsPool.Data structs used by the BondingManager // created with older versions of this library can be differentiated from EarningsPool.Data structs used by the BondingManager // created with a newer version of this library. If the flag is true, then the struct was initialized using the `init` function // using a newer version of this library meaning that it is using separate transcoder reward and fee pools struct Data { uint256 rewardPool; // Delegator rewards. If `hasTranscoderRewardFeePool` is false, this will contain transcoder rewards as well uint256 feePool; // Delegator fees. If `hasTranscoderRewardFeePool` is false, this will contain transcoder fees as well uint256 totalStake; // Transcoder's total stake during the earnings pool's round uint256 claimableStake; // Stake that can be used to claim portions of the fee and reward pools uint256 transcoderRewardCut; // Transcoder's reward cut during the earnings pool's round uint256 transcoderFeeShare; // Transcoder's fee share during the earnings pool's round uint256 transcoderRewardPool; // Transcoder rewards. If `hasTranscoderRewardFeePool` is false, this should always be 0 uint256 transcoderFeePool; // Transcoder fees. If `hasTranscoderRewardFeePool` is false, this should always be 0 bool hasTranscoderRewardFeePool; // Flag to indicate if the earnings pool has separate transcoder reward and fee pools // LIP-36 (https://github.com/livepeer/LIPs/blob/master/LIPs/LIP-36.md) fields // See EarningsPoolLIP36.sol uint256 cumulativeRewardFactor; uint256 cumulativeFeeFactor; } /** * @dev Sets transcoderRewardCut and transcoderFeeshare for an EarningsPool * @param earningsPool Storage pointer to EarningsPool struct * @param _rewardCut Reward cut of transcoder during the earnings pool's round * @param _feeShare Fee share of transcoder during the earnings pool's round */ function setCommission(EarningsPool.Data storage earningsPool, uint256 _rewardCut, uint256 _feeShare) internal { earningsPool.transcoderRewardCut = _rewardCut; earningsPool.transcoderFeeShare = _feeShare; // Prior to LIP-36, we set this flag to true here to differentiate between EarningsPool structs created using older versions of this library. // When using a version of this library after the introduction of this flag to read an EarningsPool struct created using an older version // of this library, this flag should be false in the returned struct because the default value for EVM storage is 0 // earningsPool.hasTranscoderRewardFeePool = true; } /** * @dev Sets totalStake for an EarningsPool * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Total stake of the transcoder during the earnings pool's round */ function setStake(EarningsPool.Data storage earningsPool, uint256 _stake) internal { earningsPool.totalStake = _stake; // Prior to LIP-36, we also set the claimableStake // earningsPool.claimableStake = _stake; } /** * @dev Return whether this earnings pool has claimable shares i.e. is there unclaimed stake * @param earningsPool Storage pointer to EarningsPool struct */ function hasClaimableShares(EarningsPool.Data storage earningsPool) internal view returns (bool) { return earningsPool.claimableStake > 0; } /** * @dev Returns the fee pool share for a claimant. If the claimant is a transcoder, include transcoder fees as well. * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Stake of claimant * @param _isTranscoder Flag indicating whether the claimant is a transcoder */ function feePoolShare(EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder) internal view returns (uint256) { uint256 delegatorFees = 0; uint256 transcoderFees = 0; if (earningsPool.hasTranscoderRewardFeePool) { (delegatorFees, transcoderFees) = feePoolShareWithTranscoderRewardFeePool(earningsPool, _stake, _isTranscoder); } else { (delegatorFees, transcoderFees) = feePoolShareNoTranscoderRewardFeePool(earningsPool, _stake, _isTranscoder); } return delegatorFees.add(transcoderFees); } /** * @dev Returns the reward pool share for a claimant. If the claimant is a transcoder, include transcoder rewards as well. * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Stake of claimant * @param _isTranscoder Flag indicating whether the claimant is a transcoder */ function rewardPoolShare(EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder) internal view returns (uint256) { uint256 delegatorRewards = 0; uint256 transcoderRewards = 0; if (earningsPool.hasTranscoderRewardFeePool) { (delegatorRewards, transcoderRewards) = rewardPoolShareWithTranscoderRewardFeePool(earningsPool, _stake, _isTranscoder); } else { (delegatorRewards, transcoderRewards) = rewardPoolShareNoTranscoderRewardFeePool(earningsPool, _stake, _isTranscoder); } return delegatorRewards.add(transcoderRewards); } /** * @dev Helper function to calculate fee pool share if the earnings pool has a separate transcoder fee pool * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Stake of claimant * @param _isTranscoder Flag indicating whether the claimant is a transcoder */ function feePoolShareWithTranscoderRewardFeePool( EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder ) internal view returns (uint256, uint256) { // If there is no claimable stake, the fee pool share is 0 // If there is claimable stake, calculate fee pool share based on remaining amount in fee pool, remaining claimable stake and claimant's stake uint256 delegatorFees = earningsPool.claimableStake > 0 ? MathUtils.percOf(earningsPool.feePool, _stake, earningsPool.claimableStake) : 0; // If claimant is a transcoder, include transcoder fee pool as well return _isTranscoder ? (delegatorFees, earningsPool.transcoderFeePool) : (delegatorFees, 0); } /** * @dev Helper function to calculate reward pool share if the earnings pool has a separate transcoder reward pool * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Stake of claimant * @param _isTranscoder Flag indicating whether the claimant is a transcoder */ function rewardPoolShareWithTranscoderRewardFeePool( EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder ) internal view returns (uint256, uint256) { // If there is no claimable stake, the reward pool share is 0 // If there is claimable stake, calculate reward pool share based on remaining amount in reward pool, remaining claimable stake and claimant's stake uint256 delegatorRewards = earningsPool.claimableStake > 0 ? MathUtils.percOf(earningsPool.rewardPool, _stake, earningsPool.claimableStake) : 0; // If claimant is a transcoder, include transcoder reward pool as well return _isTranscoder ? (delegatorRewards, earningsPool.transcoderRewardPool) : (delegatorRewards, 0); } /** * @dev Helper function to calculate the fee pool share if the earnings pool does not have a separate transcoder fee pool * This implements calculation logic from a previous version of this library * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Stake of claimant * @param _isTranscoder Flag indicating whether the claimant is a transcoder */ function feePoolShareNoTranscoderRewardFeePool( EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder ) internal view returns (uint256, uint256) { uint256 transcoderFees = 0; uint256 delegatorFees = 0; if (earningsPool.claimableStake > 0) { uint256 delegatorsFees = MathUtils.percOf(earningsPool.feePool, earningsPool.transcoderFeeShare); transcoderFees = earningsPool.feePool.sub(delegatorsFees); delegatorFees = MathUtils.percOf(delegatorsFees, _stake, earningsPool.claimableStake); } if (_isTranscoder) { return (delegatorFees, transcoderFees); } else { return (delegatorFees, 0); } } /** * @dev Helper function to calculate the reward pool share if the earnings pool does not have a separate transcoder reward pool * This implements calculation logic from a previous version of this library * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Stake of claimant * @param _isTranscoder Flag indicating whether the claimant is a transcoder */ function rewardPoolShareNoTranscoderRewardFeePool( EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder ) internal view returns (uint256, uint256) { uint256 transcoderRewards = 0; uint256 delegatorRewards = 0; if (earningsPool.claimableStake > 0) { transcoderRewards = MathUtils.percOf(earningsPool.rewardPool, earningsPool.transcoderRewardCut); delegatorRewards = MathUtils.percOf(earningsPool.rewardPool.sub(transcoderRewards), _stake, earningsPool.claimableStake); } if (_isTranscoder) { return (delegatorRewards, transcoderRewards); } else { return (delegatorRewards, 0); } } } // File: contracts/bonding/libraries/EarningsPoolLIP36.sol pragma solidity ^0.5.11; library EarningsPoolLIP36 { using SafeMath for uint256; /** * @notice Update the cumulative fee factor stored in an earnings pool with new fees * @param earningsPool Storage pointer to EarningsPools.Data struct * @param _prevEarningsPool In-memory EarningsPool.Data struct that stores the previous cumulative reward and fee factors * @param _fees Amount of new fees */ function updateCumulativeFeeFactor(EarningsPool.Data storage earningsPool, EarningsPool.Data memory _prevEarningsPool, uint256 _fees) internal { uint256 prevCumulativeFeeFactor = _prevEarningsPool.cumulativeFeeFactor; uint256 prevCumulativeRewardFactor = _prevEarningsPool.cumulativeRewardFactor != 0 ? _prevEarningsPool.cumulativeRewardFactor : MathUtils.percPoints(1,1); // Initialize the cumulativeFeeFactor when adding fees for the first time if (earningsPool.cumulativeFeeFactor == 0) { earningsPool.cumulativeFeeFactor = prevCumulativeFeeFactor.add( MathUtils.percOf(prevCumulativeRewardFactor, _fees, earningsPool.totalStake) ); return; } earningsPool.cumulativeFeeFactor = earningsPool.cumulativeFeeFactor.add( MathUtils.percOf(prevCumulativeRewardFactor, _fees, earningsPool.totalStake) ); } /** * @notice Update the cumulative reward factor stored in an earnings pool with new rewards * @param earningsPool Storage pointer to EarningsPool.Data struct * @param _prevEarningsPool Storage pointer to EarningsPool.Data struct that stores the previous cumulative reward factor * @param _rewards Amount of new rewards */ function updateCumulativeRewardFactor(EarningsPool.Data storage earningsPool, EarningsPool.Data storage _prevEarningsPool, uint256 _rewards) internal { uint256 prevCumulativeRewardFactor = _prevEarningsPool.cumulativeRewardFactor != 0 ? _prevEarningsPool.cumulativeRewardFactor : MathUtils.percPoints(1,1); earningsPool.cumulativeRewardFactor = prevCumulativeRewardFactor.add( MathUtils.percOf(prevCumulativeRewardFactor, _rewards, earningsPool.totalStake) ); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[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 returns (bool) { _approve(msg.sender, spender, _allowances[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 returns (bool) { _approve(msg.sender, spender, _allowances[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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } // File: contracts/token/ILivepeerToken.sol pragma solidity ^0.5.11; contract ILivepeerToken is ERC20, Ownable { function mint(address _to, uint256 _amount) public returns (bool); function burn(uint256 _amount) public; } // File: contracts/token/IMinter.sol pragma solidity ^0.5.11; /** * @title Minter interface */ contract IMinter { // Events event SetCurrentRewardTokens(uint256 currentMintableTokens, uint256 currentInflation); // External functions function createReward(uint256 _fracNum, uint256 _fracDenom) external returns (uint256); function trustedTransferTokens(address _to, uint256 _amount) external; function trustedBurnTokens(uint256 _amount) external; function trustedWithdrawETH(address payable _to, uint256 _amount) external; function depositETH() external payable returns (bool); function setCurrentRewardTokens() external; function currentMintableTokens() external view returns (uint256); function currentMintedTokens() external view returns (uint256); // Public functions function getController() public view returns (IController); } // File: contracts/rounds/IRoundsManager.sol pragma solidity ^0.5.11; /** * @title RoundsManager interface */ contract IRoundsManager { // Events event NewRound(uint256 indexed round, bytes32 blockHash); // Deprecated events // These event signatures can be used to construct the appropriate topic hashes to filter for past logs corresponding // to these deprecated events. // event NewRound(uint256 round) // External functions function initializeRound() external; function lipUpgradeRound(uint256 _lip) external view returns (uint256); // Public functions function blockNum() public view returns (uint256); function blockHash(uint256 _block) public view returns (bytes32); function blockHashForRound(uint256 _round) public view returns (bytes32); function currentRound() public view returns (uint256); function currentRoundStartBlock() public view returns (uint256); function currentRoundInitialized() public view returns (bool); function currentRoundLocked() public view returns (bool); } // File: contracts/bonding/BondingManager.sol pragma solidity 0.5.11; /** * @title BondingManager * @notice Manages bonding, transcoder and rewards/fee accounting related operations of the Livepeer protocol */ contract BondingManager is ManagerProxyTarget, IBondingManager { using SafeMath for uint256; using SortedDoublyLL for SortedDoublyLL.Data; using EarningsPool for EarningsPool.Data; using EarningsPoolLIP36 for EarningsPool.Data; // Constants // Occurances are replaced at compile time // and computed to a single value if possible by the optimizer uint256 constant MAX_FUTURE_ROUND = 2**256 - 1; // Time between unbonding and possible withdrawl in rounds uint64 public unbondingPeriod; // DEPRECATED - DO NOT USE uint256 public numActiveTranscodersDEPRECATED; // Max number of rounds that a caller can claim earnings for at once uint256 public maxEarningsClaimsRounds; // Represents a transcoder's current state struct Transcoder { uint256 lastRewardRound; // Last round that the transcoder called reward uint256 rewardCut; // % of reward paid to transcoder by a delegator uint256 feeShare; // % of fees paid to delegators by transcoder uint256 pricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE uint256 pendingRewardCutDEPRECATED; // DEPRECATED - DO NOT USE uint256 pendingFeeShareDEPRECATED; // DEPRECATED - DO NOT USE uint256 pendingPricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE mapping (uint256 => EarningsPool.Data) earningsPoolPerRound; // Mapping of round => earnings pool for the round uint256 lastActiveStakeUpdateRound; // Round for which the stake was last updated while the transcoder is active uint256 activationRound; // Round in which the transcoder became active - 0 if inactive uint256 deactivationRound; // Round in which the transcoder will become inactive uint256 activeCumulativeRewards; // The transcoder's cumulative rewards that are active in the current round uint256 cumulativeRewards; // The transcoder's cumulative rewards (earned via the its active staked rewards and its reward cut). uint256 cumulativeFees; // The transcoder's cumulative fees (earned via the its active staked rewards and its fee share) uint256 lastFeeRound; // Latest round in which the transcoder received fees } // The various states a transcoder can be in enum TranscoderStatus { NotRegistered, Registered } // Represents a delegator's current state struct Delegator { uint256 bondedAmount; // The amount of bonded tokens uint256 fees; // The amount of fees collected address delegateAddress; // The address delegated to uint256 delegatedAmount; // The amount of tokens delegated to the delegator uint256 startRound; // The round the delegator transitions to bonded phase and is delegated to someone uint256 withdrawRoundDEPRECATED; // DEPRECATED - DO NOT USE uint256 lastClaimRound; // The last round during which the delegator claimed its earnings uint256 nextUnbondingLockId; // ID for the next unbonding lock created mapping (uint256 => UnbondingLock) unbondingLocks; // Mapping of unbonding lock ID => unbonding lock } // The various states a delegator can be in enum DelegatorStatus { Pending, Bonded, Unbonded } // Represents an amount of tokens that are being unbonded struct UnbondingLock { uint256 amount; // Amount of tokens being unbonded uint256 withdrawRound; // Round at which unbonding period is over and tokens can be withdrawn } // Keep track of the known transcoders and delegators mapping (address => Delegator) private delegators; mapping (address => Transcoder) private transcoders; // DEPRECATED - DO NOT USE // The function getTotalBonded() no longer uses this variable // and instead calculates the total bonded value separately uint256 private totalBondedDEPRECATED; // DEPRECATED - DO NOT USE SortedDoublyLL.Data private transcoderPoolDEPRECATED; // DEPRECATED - DO NOT USE struct ActiveTranscoderSetDEPRECATED { address[] transcoders; mapping (address => bool) isActive; uint256 totalStake; } // DEPRECATED - DO NOT USE mapping (uint256 => ActiveTranscoderSetDEPRECATED) public activeTranscoderSetDEPRECATED; // The total active stake (sum of the stake of active set members) for the current round uint256 public currentRoundTotalActiveStake; // The total active stake (sum of the stake of active set members) for the next round uint256 public nextRoundTotalActiveStake; // The transcoder pool is used to keep track of the transcoders that are eligible for activation. // The pool keeps track of the pending active set in round N and the start of round N + 1 transcoders // in the pool are locked into the active set for round N + 1 SortedDoublyLL.Data private transcoderPoolV2; // Check if sender is TicketBroker modifier onlyTicketBroker() { require( msg.sender == controller.getContract(keccak256("TicketBroker")), "caller must be TicketBroker" ); _; } // Check if sender is RoundsManager modifier onlyRoundsManager() { require( msg.sender == controller.getContract(keccak256("RoundsManager")), "caller must be RoundsManager" ); _; } // Check if sender is Verifier modifier onlyVerifier() { require(msg.sender == controller.getContract(keccak256("Verifier")), "caller must be Verifier"); _; } // Check if current round is initialized modifier currentRoundInitialized() { require(roundsManager().currentRoundInitialized(), "current round is not initialized"); _; } // Automatically claim earnings from lastClaimRound through the current round modifier autoClaimEarnings() { uint256 currentRound = roundsManager().currentRound(); uint256 lastClaimRound = delegators[msg.sender].lastClaimRound; if (lastClaimRound < currentRound) { updateDelegatorWithEarnings(msg.sender, currentRound, lastClaimRound); } _; } /** * @notice BondingManager constructor. Only invokes constructor of base Manager contract with provided Controller address * @dev This constructor will not initialize any state variables besides `controller`. The following setter functions * should be used to initialize state variables post-deployment: * - setUnbondingPeriod() * - setNumActiveTranscoders() * - setMaxEarningsClaimsRounds() * @param _controller Address of Controller that this contract will be registered with */ constructor(address _controller) public Manager(_controller) {} /** * @notice Set unbonding period. Only callable by Controller owner * @param _unbondingPeriod Rounds between unbonding and possible withdrawal */ function setUnbondingPeriod(uint64 _unbondingPeriod) external onlyControllerOwner { unbondingPeriod = _unbondingPeriod; emit ParameterUpdate("unbondingPeriod"); } /** * @notice Set maximum number of active transcoders. Only callable by Controller owner * @param _numActiveTranscoders Number of active transcoders */ function setNumActiveTranscoders(uint256 _numActiveTranscoders) external onlyControllerOwner { transcoderPoolV2.setMaxSize(_numActiveTranscoders); emit ParameterUpdate("numActiveTranscoders"); } /** * @notice Set max number of rounds a caller can claim earnings for at once. Only callable by Controller owner * @param _maxEarningsClaimsRounds Max number of rounds a caller can claim earnings for at once */ function setMaxEarningsClaimsRounds(uint256 _maxEarningsClaimsRounds) external onlyControllerOwner { maxEarningsClaimsRounds = _maxEarningsClaimsRounds; emit ParameterUpdate("maxEarningsClaimsRounds"); } /** * @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it * @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR * @param _rewardCut % of reward paid to transcoder by a delegator * @param _feeShare % of fees paid to delegators by a transcoder */ function transcoder(uint256 _rewardCut, uint256 _feeShare) external { transcoderWithHint(_rewardCut, _feeShare, address(0), address(0)); } /** * @notice Delegate stake towards a specific address * @param _amount The amount of tokens to stake * @param _to The address of the transcoder to stake towards */ function bond(uint256 _amount, address _to) external { bondWithHint( _amount, _to, address(0), address(0), address(0), address(0) ); } /** * @notice Unbond an amount of the delegator's bonded stake * @param _amount Amount of tokens to unbond */ function unbond(uint256 _amount) external { unbondWithHint(_amount, address(0), address(0)); } /** * @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status * @param _unbondingLockId ID of unbonding lock to rebond with */ function rebond(uint256 _unbondingLockId) external { rebondWithHint(_unbondingLockId, address(0), address(0)); } /** * @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status * @param _to Address of delegate * @param _unbondingLockId ID of unbonding lock to rebond with */ function rebondFromUnbonded(address _to, uint256 _unbondingLockId) external { rebondFromUnbondedWithHint(_to, _unbondingLockId, address(0), address(0)); } /** * @notice Withdraws tokens for an unbonding lock that has existed through an unbonding period * @param _unbondingLockId ID of unbonding lock to withdraw with */ function withdrawStake(uint256 _unbondingLockId) external whenSystemNotPaused currentRoundInitialized { Delegator storage del = delegators[msg.sender]; UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId]; require(isValidUnbondingLock(msg.sender, _unbondingLockId), "invalid unbonding lock ID"); require(lock.withdrawRound <= roundsManager().currentRound(), "withdraw round must be before or equal to the current round"); uint256 amount = lock.amount; uint256 withdrawRound = lock.withdrawRound; // Delete unbonding lock delete del.unbondingLocks[_unbondingLockId]; // Tell Minter to transfer stake (LPT) to the delegator minter().trustedTransferTokens(msg.sender, amount); emit WithdrawStake(msg.sender, _unbondingLockId, amount, withdrawRound); } /** * @notice Withdraws fees to the caller */ function withdrawFees() external whenSystemNotPaused currentRoundInitialized autoClaimEarnings { uint256 fees = delegators[msg.sender].fees; require(fees > 0, "no fees to withdraw"); delegators[msg.sender].fees = 0; // Tell Minter to transfer fees (ETH) to the delegator minter().trustedWithdrawETH(msg.sender, fees); emit WithdrawFees(msg.sender); } /** * @notice Mint token rewards for an active transcoder and its delegators */ function reward() external { rewardWithHint(address(0), address(0)); } /** * @notice Update transcoder's fee pool. Only callable by the TicketBroker * @param _transcoder Transcoder address * @param _fees Fees to be added to the fee pool */ function updateTranscoderWithFees( address _transcoder, uint256 _fees, uint256 _round ) external whenSystemNotPaused onlyTicketBroker { // Silence unused param compiler warning _round; require(isRegisteredTranscoder(_transcoder), "transcoder must be registered"); uint256 currentRound = roundsManager().currentRound(); Transcoder storage t = transcoders[_transcoder]; uint256 lastRewardRound = t.lastRewardRound; uint256 activeCumulativeRewards = t.activeCumulativeRewards; // LIP-36: Add fees for the current round instead of '_round' // https://github.com/livepeer/LIPs/issues/35#issuecomment-673659199 EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound]; EarningsPool.Data memory prevEarningsPool = latestCumulativeFactorsPool(t, currentRound.sub(1)); // if transcoder hasn't called 'reward()' for '_round' its 'transcoderFeeShare', 'transcoderRewardCut' and 'totalStake' // on the 'EarningsPool' for '_round' would not be initialized and the fee distribution wouldn't happen as expected // for cumulative fee calculation this would result in division by zero. if (currentRound > lastRewardRound) { earningsPool.setCommission( t.rewardCut, t.feeShare ); uint256 lastUpdateRound = t.lastActiveStakeUpdateRound; if (lastUpdateRound < currentRound) { earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake); } // If reward() has not been called yet in the current round, then the transcoder's activeCumulativeRewards has not // yet been set in for the round. When the transcoder calls reward() its activeCumulativeRewards will be set to its // current cumulativeRewards. So, we can just use the transcoder's cumulativeRewards here because this will become // the transcoder's activeCumulativeRewards if it calls reward() later on in the current round activeCumulativeRewards = t.cumulativeRewards; } uint256 totalStake = earningsPool.totalStake; if (prevEarningsPool.cumulativeRewardFactor == 0 && lastRewardRound == currentRound) { // if transcoder called reward for 'currentRound' but not for 'currentRound - 1' (missed reward call) // retroactively calculate what its cumulativeRewardFactor would have been for 'currentRound - 1' (cfr. previous lastRewardRound for transcoder) // based on rewards for currentRound IMinter mtr = minter(); uint256 rewards = MathUtils.percOf(mtr.currentMintableTokens().add(mtr.currentMintedTokens()), totalStake, currentRoundTotalActiveStake); uint256 transcoderCommissionRewards = MathUtils.percOf(rewards, earningsPool.transcoderRewardCut); uint256 delegatorsRewards = rewards.sub(transcoderCommissionRewards); prevEarningsPool.cumulativeRewardFactor = MathUtils.percOf( earningsPool.cumulativeRewardFactor, totalStake, delegatorsRewards.add(totalStake) ); } uint256 delegatorsFees = MathUtils.percOf(_fees, earningsPool.transcoderFeeShare); uint256 transcoderCommissionFees = _fees.sub(delegatorsFees); // Calculate the fees earned by the transcoder's earned rewards uint256 transcoderRewardStakeFees = MathUtils.percOf(delegatorsFees, activeCumulativeRewards, totalStake); // Track fees earned by the transcoder based on its earned rewards and feeShare t.cumulativeFees = t.cumulativeFees.add(transcoderRewardStakeFees).add(transcoderCommissionFees); // Update cumulative fee factor with new fees // The cumulativeFeeFactor is used to calculate fees for all delegators including the transcoder (self-delegated) // Note that delegatorsFees includes transcoderRewardStakeFees, but no delegator will claim that amount using // the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeFees field earningsPool.updateCumulativeFeeFactor(prevEarningsPool, delegatorsFees); t.lastFeeRound = currentRound; } /** * @notice Slash a transcoder. Only callable by the Verifier * @param _transcoder Transcoder address * @param _finder Finder that proved a transcoder violated a slashing condition. Null address if there is no finder * @param _slashAmount Percentage of transcoder bond to be slashed * @param _finderFee Percentage of penalty awarded to finder. Zero if there is no finder */ function slashTranscoder( address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee ) external whenSystemNotPaused onlyVerifier { Delegator storage del = delegators[_transcoder]; if (del.bondedAmount > 0) { uint256 penalty = MathUtils.percOf(delegators[_transcoder].bondedAmount, _slashAmount); // If active transcoder, resign it if (transcoderPoolV2.contains(_transcoder)) { resignTranscoder(_transcoder); } // Decrease bonded stake del.bondedAmount = del.bondedAmount.sub(penalty); // If still bonded decrease delegate's delegated amount if (delegatorStatus(_transcoder) == DelegatorStatus.Bonded) { delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(penalty); } // Account for penalty uint256 burnAmount = penalty; // Award finder fee if there is a finder address if (_finder != address(0)) { uint256 finderAmount = MathUtils.percOf(penalty, _finderFee); minter().trustedTransferTokens(_finder, finderAmount); // Minter burns the slashed funds - finder reward minter().trustedBurnTokens(burnAmount.sub(finderAmount)); emit TranscoderSlashed(_transcoder, _finder, penalty, finderAmount); } else { // Minter burns the slashed funds minter().trustedBurnTokens(burnAmount); emit TranscoderSlashed(_transcoder, address(0), penalty, 0); } } else { emit TranscoderSlashed(_transcoder, _finder, 0, 0); } } /** * @notice Claim token pools shares for a delegator from its lastClaimRound through the end round * @param _endRound The last round for which to claim token pools shares for a delegator */ function claimEarnings(uint256 _endRound) external whenSystemNotPaused currentRoundInitialized { uint256 lastClaimRound = delegators[msg.sender].lastClaimRound; require(lastClaimRound < _endRound, "end round must be after last claim round"); require(_endRound <= roundsManager().currentRound(), "end round must be before or equal to current round"); updateDelegatorWithEarnings(msg.sender, _endRound, lastClaimRound); } /** * @notice Called during round initialization to set the total active stake for the round. Only callable by the RoundsManager */ function setCurrentRoundTotalActiveStake() external onlyRoundsManager { currentRoundTotalActiveStake = nextRoundTotalActiveStake; } /** * @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it using an optional list hint * @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR. If the caller is going to be added to the pool, the * caller can provide an optional hint for the insertion position in the pool via the `_newPosPrev` and `_newPosNext` params. A linear search will * be executed starting at the hint to find the correct position - in the best case, the hint is the correct position so no search is executed. * See SortedDoublyLL.sol for details on list hints * @param _rewardCut % of reward paid to transcoder by a delegator * @param _feeShare % of fees paid to delegators by a transcoder * @param _newPosPrev Address of previous transcoder in pool if the caller joins the pool * @param _newPosNext Address of next transcoder in pool if the caller joins the pool */ function transcoderWithHint(uint256 _rewardCut, uint256 _feeShare, address _newPosPrev, address _newPosNext) public whenSystemNotPaused currentRoundInitialized { require( !roundsManager().currentRoundLocked(), "can't update transcoder params, current round is locked" ); require(MathUtils.validPerc(_rewardCut), "invalid rewardCut percentage"); require(MathUtils.validPerc(_feeShare), "invalid feeShare percentage"); require(isRegisteredTranscoder(msg.sender), "transcoder must be registered"); Transcoder storage t = transcoders[msg.sender]; uint256 currentRound = roundsManager().currentRound(); require( !isActiveTranscoder(msg.sender) || t.lastRewardRound == currentRound, "caller can't be active or must have already called reward for the current round" ); t.rewardCut = _rewardCut; t.feeShare = _feeShare; if (!transcoderPoolV2.contains(msg.sender)) { tryToJoinActiveSet(msg.sender, delegators[msg.sender].delegatedAmount, currentRound.add(1), _newPosPrev, _newPosNext); } emit TranscoderUpdate(msg.sender, _rewardCut, _feeShare); } /** * @notice Delegate stake towards a specific address and updates the transcoder pool using optional list hints if needed * @dev If the caller is decreasing the stake of its old delegate in the transcoder pool, the caller can provide an optional hint * for the insertion position of the old delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params. * If the caller is delegating to a delegate that is in the transcoder pool, the caller can provide an optional hint for the * insertion position of the delegate via the `_currDelegateNewPosPrev` and `_currDelegateNewPosNext` params. * In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint * is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints * @param _amount The amount of tokens to stake. * @param _to The address of the transcoder to stake towards * @param _oldDelegateNewPosPrev The address of the previous transcoder in the pool for the old delegate * @param _oldDelegateNewPosNext The address of the next transcoder in the pool for the old delegate * @param _currDelegateNewPosPrev The address of the previous transcoder in the pool for the current delegate * @param _currDelegateNewPosNext The address of the next transcoder in the pool for the current delegate */ function bondWithHint( uint256 _amount, address _to, address _oldDelegateNewPosPrev, address _oldDelegateNewPosNext, address _currDelegateNewPosPrev, address _currDelegateNewPosNext ) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { Delegator storage del = delegators[msg.sender]; uint256 currentRound = roundsManager().currentRound(); // Amount to delegate uint256 delegationAmount = _amount; // Current delegate address currentDelegate = del.delegateAddress; if (delegatorStatus(msg.sender) == DelegatorStatus.Unbonded) { // New delegate // Set start round // Don't set start round if delegator is in pending state because the start round would not change del.startRound = currentRound.add(1); // Unbonded state = no existing delegate and no bonded stake // Thus, delegation amount = provided amount } else if (currentDelegate != address(0) && currentDelegate != _to) { // A registered transcoder cannot delegate its bonded stake toward another address // because it can only be delegated toward itself // In the future, if delegation towards another registered transcoder as an already // registered transcoder becomes useful (i.e. for transitive delegation), this restriction // could be removed require(!isRegisteredTranscoder(msg.sender), "registered transcoders can't delegate towards other addresses"); // Changing delegate // Set start round del.startRound = currentRound.add(1); // Update amount to delegate with previous delegation amount delegationAmount = delegationAmount.add(del.bondedAmount); decreaseTotalStake(currentDelegate, del.bondedAmount, _oldDelegateNewPosPrev, _oldDelegateNewPosNext); } // cannot delegate to someone without having bonded stake require(delegationAmount > 0, "delegation amount must be greater than 0"); // Update delegate del.delegateAddress = _to; // Update bonded amount del.bondedAmount = del.bondedAmount.add(_amount); increaseTotalStake(_to, delegationAmount, _currDelegateNewPosPrev, _currDelegateNewPosNext); if (_amount > 0) { // Transfer the LPT to the Minter livepeerToken().transferFrom(msg.sender, address(minter()), _amount); } emit Bond(_to, currentDelegate, msg.sender, _amount, del.bondedAmount); } /** * @notice Unbond an amount of the delegator's bonded stake and updates the transcoder pool using an optional list hint if needed * @dev If the caller remains in the transcoder pool, the caller can provide an optional hint for its insertion position in the * pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. * In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints * @param _amount Amount of tokens to unbond * @param _newPosPrev Address of previous transcoder in pool if the caller remains in the pool * @param _newPosNext Address of next transcoder in pool if the caller remains in the pool */ function unbondWithHint(uint256 _amount, address _newPosPrev, address _newPosNext) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { require(delegatorStatus(msg.sender) == DelegatorStatus.Bonded, "caller must be bonded"); Delegator storage del = delegators[msg.sender]; require(_amount > 0, "unbond amount must be greater than 0"); require(_amount <= del.bondedAmount, "amount is greater than bonded amount"); address currentDelegate = del.delegateAddress; uint256 currentRound = roundsManager().currentRound(); uint256 withdrawRound = currentRound.add(unbondingPeriod); uint256 unbondingLockId = del.nextUnbondingLockId; // Create new unbonding lock del.unbondingLocks[unbondingLockId] = UnbondingLock({ amount: _amount, withdrawRound: withdrawRound }); // Increment ID for next unbonding lock del.nextUnbondingLockId = unbondingLockId.add(1); // Decrease delegator's bonded amount del.bondedAmount = del.bondedAmount.sub(_amount); if (del.bondedAmount == 0) { // Delegator no longer delegated to anyone if it does not have a bonded amount del.delegateAddress = address(0); // Delegator does not have a start round if it is no longer delegated to anyone del.startRound = 0; if (transcoderPoolV2.contains(msg.sender)) { resignTranscoder(msg.sender); } } // If msg.sender was resigned this statement will only decrease delegators[currentDelegate].delegatedAmount decreaseTotalStake(currentDelegate, _amount, _newPosPrev, _newPosNext); emit Unbond(currentDelegate, msg.sender, unbondingLockId, _amount, withdrawRound); } /** * @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status and updates * the transcoder pool using an optional list hint if needed * @dev If the delegate is in the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the * pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. * In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints * @param _unbondingLockId ID of unbonding lock to rebond with * @param _newPosPrev Address of previous transcoder in pool if the delegate is in the pool * @param _newPosNext Address of next transcoder in pool if the delegate is in the pool */ function rebondWithHint( uint256 _unbondingLockId, address _newPosPrev, address _newPosNext ) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { require(delegatorStatus(msg.sender) != DelegatorStatus.Unbonded, "caller must be bonded"); // Process rebond using unbonding lock processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext); } /** * @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status and updates the transcoder pool using * an optional list hint if needed * @dev If the delegate joins the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the * pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. * In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints * @param _to Address of delegate * @param _unbondingLockId ID of unbonding lock to rebond with * @param _newPosPrev Address of previous transcoder in pool if the delegate joins the pool * @param _newPosNext Address of next transcoder in pool if the delegate joins the pool */ function rebondFromUnbondedWithHint( address _to, uint256 _unbondingLockId, address _newPosPrev, address _newPosNext ) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded, "caller must be unbonded"); // Set delegator's start round and transition into Pending state delegators[msg.sender].startRound = roundsManager().currentRound().add(1); // Set delegator's delegate delegators[msg.sender].delegateAddress = _to; // Process rebond using unbonding lock processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext); } /** * @notice Mint token rewards for an active transcoder and its delegators and update the transcoder pool using an optional list hint if needed * @dev If the caller is in the transcoder pool, the caller can provide an optional hint for its insertion position in the * pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. * In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints * @param _newPosPrev Address of previous transcoder in pool if the caller is in the pool * @param _newPosNext Address of next transcoder in pool if the caller is in the pool */ function rewardWithHint(address _newPosPrev, address _newPosNext) public whenSystemNotPaused currentRoundInitialized { uint256 currentRound = roundsManager().currentRound(); require(isActiveTranscoder(msg.sender), "caller must be an active transcoder"); require(transcoders[msg.sender].lastRewardRound != currentRound, "caller has already called reward for the current round"); Transcoder storage t = transcoders[msg.sender]; EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound]; // Set last round that transcoder called reward earningsPool.setCommission(t.rewardCut, t.feeShare); // If transcoder didn't receive stake updates during the previous round and hasn't called reward for > 1 round // the 'totalStake' on its 'EarningsPool' for the current round wouldn't be initialized // Thus we sync the the transcoder's stake to when it was last updated // 'updateTrancoderWithRewards()' will set the update round to 'currentRound +1' so this synchronization shouldn't occur frequently uint256 lastUpdateRound = t.lastActiveStakeUpdateRound; if (lastUpdateRound < currentRound) { earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake); } // Create reward based on active transcoder's stake relative to the total active stake // rewardTokens = (current mintable tokens for the round * active transcoder stake) / total active stake uint256 rewardTokens = minter().createReward(earningsPool.totalStake, currentRoundTotalActiveStake); updateTranscoderWithRewards(msg.sender, rewardTokens, currentRound, _newPosPrev, _newPosNext); // Set last round that transcoder called reward t.lastRewardRound = currentRound; emit Reward(msg.sender, rewardTokens); } /** * @notice Returns pending bonded stake for a delegator from its lastClaimRound through an end round * @param _delegator Address of delegator * @param _endRound The last round to compute pending stake from * @return Pending bonded stake for '_delegator' since last claiming rewards */ function pendingStake(address _delegator, uint256 _endRound) public view returns (uint256) { ( uint256 stake, ) = pendingStakeAndFees(_delegator, _endRound); return stake; } /** * @notice Returns pending fees for a delegator from its lastClaimRound through an end round * @param _delegator Address of delegator * @param _endRound The last round to compute pending fees from * @return Pending fees for '_delegator' since last claiming fees */ function pendingFees(address _delegator, uint256 _endRound) public view returns (uint256) { ( , uint256 fees ) = pendingStakeAndFees(_delegator, _endRound); return fees; } /** * @notice Returns total bonded stake for a transcoder * @param _transcoder Address of transcoder * @return total bonded stake for a delegator */ function transcoderTotalStake(address _transcoder) public view returns (uint256) { return delegators[_transcoder].delegatedAmount; } /** * @notice Computes transcoder status * @param _transcoder Address of transcoder * @return registered or not registered transcoder status */ function transcoderStatus(address _transcoder) public view returns (TranscoderStatus) { if (isRegisteredTranscoder(_transcoder)) return TranscoderStatus.Registered; return TranscoderStatus.NotRegistered; } /** * @notice Computes delegator status * @param _delegator Address of delegator * @return bonded, unbonded or pending delegator status */ function delegatorStatus(address _delegator) public view returns (DelegatorStatus) { Delegator storage del = delegators[_delegator]; if (del.bondedAmount == 0) { // Delegator unbonded all its tokens return DelegatorStatus.Unbonded; } else if (del.startRound > roundsManager().currentRound()) { // Delegator round start is in the future return DelegatorStatus.Pending; } else { // Delegator round start is now or in the past // del.startRound != 0 here because if del.startRound = 0 then del.bondedAmount = 0 which // would trigger the first if clause return DelegatorStatus.Bonded; } } /** * @notice Return transcoder information * @param _transcoder Address of transcoder * @return lastRewardRound Trancoder's last reward round * @return rewardCut Transcoder's reward cut * @return feeShare Transcoder's fee share * @return lastActiveStakeUpdateRound Round in which transcoder's stake was last updated while active * @return activationRound Round in which transcoder became active * @return deactivationRound Round in which transcoder will no longer be active * @return activeCumulativeRewards Transcoder's cumulative rewards that are currently active * @return cumulativeRewards Transcoder's cumulative rewards (earned via its active staked rewards and its reward cut) * @return cumulativeFees Transcoder's cumulative fees (earned via its active staked rewards and its fee share) * @return lastFeeRound Latest round that the transcoder received fees */ function getTranscoder( address _transcoder ) public view returns (uint256 lastRewardRound, uint256 rewardCut, uint256 feeShare, uint256 lastActiveStakeUpdateRound, uint256 activationRound, uint256 deactivationRound, uint256 activeCumulativeRewards, uint256 cumulativeRewards, uint256 cumulativeFees, uint256 lastFeeRound) { Transcoder storage t = transcoders[_transcoder]; lastRewardRound = t.lastRewardRound; rewardCut = t.rewardCut; feeShare = t.feeShare; lastActiveStakeUpdateRound = t.lastActiveStakeUpdateRound; activationRound = t.activationRound; deactivationRound = t.deactivationRound; activeCumulativeRewards = t.activeCumulativeRewards; cumulativeRewards = t.cumulativeRewards; cumulativeFees = t.cumulativeFees; lastFeeRound = t.lastFeeRound; } /** * @notice Return transcoder's earnings pool for a given round * @param _transcoder Address of transcoder * @param _round Round number * @return rewardPool Reward pool for delegators (only used before LIP-36) * @return feePool Fee pool for delegators (only used before LIP-36) * @return totalStake Transcoder's total stake in '_round' * @return claimableStake Remaining stake that can be used to claim from the pool (only used before LIP-36) * @return transcoderRewardCut Transcoder's reward cut for '_round' * @return transcoderFeeShare Transcoder's fee share for '_round' * @return transcoderRewardPool Transcoder's rewards for '_round' (only used before LIP-36) * @return transcoderFeePool Transcoder's fees for '_round' (only used before LIP-36) * @return hasTranscoderRewardFeePool True if there is a split reward/fee pool for the transcoder (only used before LIP-36) * @return cumulativeRewardFactor The cumulative reward factor for delegator rewards calculation (only used after LIP-36) * @return cumulativeFeeFactor The cumulative fee factor for delegator fees calculation (only used after LIP-36) */ function getTranscoderEarningsPoolForRound( address _transcoder, uint256 _round ) public view returns (uint256 rewardPool, uint256 feePool, uint256 totalStake, uint256 claimableStake, uint256 transcoderRewardCut, uint256 transcoderFeeShare, uint256 transcoderRewardPool, uint256 transcoderFeePool, bool hasTranscoderRewardFeePool, uint256 cumulativeRewardFactor, uint256 cumulativeFeeFactor) { EarningsPool.Data storage earningsPool = transcoders[_transcoder].earningsPoolPerRound[_round]; rewardPool = earningsPool.rewardPool; feePool = earningsPool.feePool; totalStake = earningsPool.totalStake; claimableStake = earningsPool.claimableStake; transcoderRewardCut = earningsPool.transcoderRewardCut; transcoderFeeShare = earningsPool.transcoderFeeShare; transcoderRewardPool = earningsPool.transcoderRewardPool; transcoderFeePool = earningsPool.transcoderFeePool; hasTranscoderRewardFeePool = earningsPool.hasTranscoderRewardFeePool; cumulativeRewardFactor = earningsPool.cumulativeRewardFactor; cumulativeFeeFactor = earningsPool.cumulativeFeeFactor; } /** * @notice Return delegator info * @param _delegator Address of delegator * @return total amount bonded by '_delegator' * @return amount of fees collected by '_delegator' * @return address '_delegator' has bonded to * @return total amount delegated to '_delegator' * @return round in which bond for '_delegator' became effective * @return round for which '_delegator' has last claimed earnings * @return ID for the next unbonding lock created for '_delegator' */ function getDelegator( address _delegator ) public view returns (uint256 bondedAmount, uint256 fees, address delegateAddress, uint256 delegatedAmount, uint256 startRound, uint256 lastClaimRound, uint256 nextUnbondingLockId) { Delegator storage del = delegators[_delegator]; bondedAmount = del.bondedAmount; fees = del.fees; delegateAddress = del.delegateAddress; delegatedAmount = del.delegatedAmount; startRound = del.startRound; lastClaimRound = del.lastClaimRound; nextUnbondingLockId = del.nextUnbondingLockId; } /** * @notice Return delegator's unbonding lock info * @param _delegator Address of delegator * @param _unbondingLockId ID of unbonding lock * @return amount of stake locked up by unbonding lock * @return round in which 'amount' becomes available for withdrawal */ function getDelegatorUnbondingLock( address _delegator, uint256 _unbondingLockId ) public view returns (uint256 amount, uint256 withdrawRound) { UnbondingLock storage lock = delegators[_delegator].unbondingLocks[_unbondingLockId]; return (lock.amount, lock.withdrawRound); } /** * @notice Returns max size of transcoder pool * @return transcoder pool max size */ function getTranscoderPoolMaxSize() public view returns (uint256) { return transcoderPoolV2.getMaxSize(); } /** * @notice Returns size of transcoder pool * @return transcoder pool current size */ function getTranscoderPoolSize() public view returns (uint256) { return transcoderPoolV2.getSize(); } /** * @notice Returns transcoder with most stake in pool * @return address for transcoder with highest stake in transcoder pool */ function getFirstTranscoderInPool() public view returns (address) { return transcoderPoolV2.getFirst(); } /** * @notice Returns next transcoder in pool for a given transcoder * @param _transcoder Address of a transcoder in the pool * @return address for the transcoder after '_transcoder' in transcoder pool */ function getNextTranscoderInPool(address _transcoder) public view returns (address) { return transcoderPoolV2.getNext(_transcoder); } /** * @notice Return total bonded tokens * @return total active stake for the current round */ function getTotalBonded() public view returns (uint256) { return currentRoundTotalActiveStake; } /** * @notice Return whether a transcoder is active for the current round * @param _transcoder Transcoder address * @return true if transcoder is active */ function isActiveTranscoder(address _transcoder) public view returns (bool) { Transcoder storage t = transcoders[_transcoder]; uint256 currentRound = roundsManager().currentRound(); return t.activationRound <= currentRound && currentRound < t.deactivationRound; } /** * @notice Return whether a transcoder is registered * @param _transcoder Transcoder address * @return true if transcoder is self-bonded */ function isRegisteredTranscoder(address _transcoder) public view returns (bool) { Delegator storage d = delegators[_transcoder]; return d.delegateAddress == _transcoder && d.bondedAmount > 0; } /** * @notice Return whether an unbonding lock for a delegator is valid * @param _delegator Address of delegator * @param _unbondingLockId ID of unbonding lock * @return true if unbondingLock for ID has a non-zero withdraw round */ function isValidUnbondingLock(address _delegator, uint256 _unbondingLockId) public view returns (bool) { // A unbonding lock is only valid if it has a non-zero withdraw round (the default value is zero) return delegators[_delegator].unbondingLocks[_unbondingLockId].withdrawRound > 0; } /** * @notice Return an EarningsPool.Data struct with the latest cumulative factors for a given round * @param _transcoder Storage pointer to a transcoder struct * @param _round The round to fetch the latest cumulative factors for * @return pool An EarningsPool.Data populated with the latest cumulative factors for _round */ function latestCumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round) internal view returns (EarningsPool.Data memory pool) { pool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[_round].cumulativeRewardFactor; pool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[_round].cumulativeFeeFactor; uint256 lastRewardRound = _transcoder.lastRewardRound; // Only use the cumulativeRewardFactor for lastRewardRound if lastRewardRound is before _round if (pool.cumulativeRewardFactor == 0 && lastRewardRound < _round) { pool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[lastRewardRound].cumulativeRewardFactor; } uint256 lastFeeRound = _transcoder.lastFeeRound; // Only use the cumulativeFeeFactor for lastFeeRound if lastFeeRound is before _round if (pool.cumulativeFeeFactor == 0 && lastFeeRound < _round) { pool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[lastFeeRound].cumulativeFeeFactor; } return pool; } /** * @notice Return a delegator's cumulative stake and fees using the LIP-36 earnings claiming algorithm * @param _transcoder Storage pointer to a transcoder struct for a delegator's delegate * @param _startRound The round for the start cumulative factors * @param _endRound The round for the end cumulative factors * @param _stake The delegator's initial stake before including earned rewards * @param _fees The delegator's initial fees before including earned fees * @return (cStake, cFees) where cStake is the delegator's cumulative stake including earned rewards and cFees is the delegator's cumulative fees including earned fees */ function delegatorCumulativeStakeAndFees( Transcoder storage _transcoder, uint256 _startRound, uint256 _endRound, uint256 _stake, uint256 _fees ) internal view returns (uint256 cStake, uint256 cFees) { uint256 baseRewardFactor = MathUtils.percPoints(1, 1); // Fetch start cumulative factors EarningsPool.Data memory startPool; startPool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[_startRound].cumulativeRewardFactor; startPool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[_startRound].cumulativeFeeFactor; if (startPool.cumulativeRewardFactor == 0) { startPool.cumulativeRewardFactor = baseRewardFactor; } // Fetch end cumulative factors EarningsPool.Data memory endPool = latestCumulativeFactorsPool(_transcoder, _endRound); if (endPool.cumulativeRewardFactor == 0) { endPool.cumulativeRewardFactor = baseRewardFactor; } cFees = _fees.add( MathUtils.percOf( _stake, endPool.cumulativeFeeFactor.sub(startPool.cumulativeFeeFactor), startPool.cumulativeRewardFactor ) ); cStake = MathUtils.percOf( _stake, endPool.cumulativeRewardFactor, startPool.cumulativeRewardFactor ); return (cStake, cFees); } /** * @notice Return the pending stake and fees for a delegator * @param _delegator Address of a delegator * @param _endRound The last round to claim earnings for when calculating the pending stake and fees * @return (stake, fees) where stake is the delegator's pending stake and fees is the delegator's pending fees */ function pendingStakeAndFees(address _delegator, uint256 _endRound) internal view returns (uint256 stake, uint256 fees) { Delegator storage del = delegators[_delegator]; Transcoder storage t = transcoders[del.delegateAddress]; fees = del.fees; stake = del.bondedAmount; uint256 startRound = del.lastClaimRound.add(1); address delegateAddr = del.delegateAddress; bool isTranscoder = _delegator == delegateAddr; uint256 lip36Round = roundsManager().lipUpgradeRound(36); while (startRound <= _endRound && startRound <= lip36Round) { EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[startRound]; // If earningsPool.hasTranscoderRewardFeePool is not set during lip36Round then the transcoder did not call // reward during lip36Round before the upgrade. In this case, if the transcoder calls reward in lip36Round // the delegator can use the LIP-36 earnings claiming algorithm to claim for lip36Round if (startRound == lip36Round && !earningsPool.hasTranscoderRewardFeePool) { break; } if (earningsPool.hasClaimableShares()) { // Calculate and add fee pool share from this round fees = fees.add(earningsPool.feePoolShare(stake, isTranscoder)); // Calculate new bonded amount with rewards from this round. Updated bonded amount used // to calculate fee pool share in next round stake = stake.add(earningsPool.rewardPoolShare(stake, isTranscoder)); } startRound = startRound.add(1); } // If the transcoder called reward during lip36Round the upgrade, then startRound = lip36Round // Otherwise, startRound = lip36Round + 1 // If the start round is greater than the end round, we've already claimed for the end round so we do not // need to execute the LIP-36 earnings claiming algorithm. This could be the case if: // - _endRound < lip36Round i.e. we are not claiming through the lip36Round // - _endRound == lip36Round AND startRound = lip36Round + 1 i.e we already claimed through the lip36Round if (startRound > _endRound) { return (stake, fees); } // The LIP-36 earnings claiming algorithm uses the cumulative factors from the delegator's lastClaimRound i.e. startRound - 1 // and from the specified _endRound ( stake, fees ) = delegatorCumulativeStakeAndFees(t, startRound.sub(1), _endRound, stake, fees); if (isTranscoder) { stake = stake.add(t.cumulativeRewards); fees = fees.add(t.cumulativeFees); } return (stake, fees); } /** * @dev Increase the total stake for a delegate and updates its 'lastActiveStakeUpdateRound' * @param _delegate The delegate to increase the stake for * @param _amount The amount to increase the stake for '_delegate' by */ function increaseTotalStake(address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext) internal { if (isRegisteredTranscoder(_delegate)) { uint256 currStake = transcoderTotalStake(_delegate); uint256 newStake = currStake.add(_amount); uint256 currRound = roundsManager().currentRound(); uint256 nextRound = currRound.add(1); // If the transcoder is already in the active set update its stake and return if (transcoderPoolV2.contains(_delegate)) { transcoderPoolV2.updateKey(_delegate, newStake, _newPosPrev, _newPosNext); nextRoundTotalActiveStake = nextRoundTotalActiveStake.add(_amount); Transcoder storage t = transcoders[_delegate]; // currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound // because it is updated every time lastActiveStakeUpdateRound is updated // The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards() // and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound if (t.lastActiveStakeUpdateRound < currRound) { t.earningsPoolPerRound[currRound].setStake(currStake); } t.earningsPoolPerRound[nextRound].setStake(newStake); t.lastActiveStakeUpdateRound = nextRound; } else { // Check if the transcoder is eligible to join the active set in the update round tryToJoinActiveSet(_delegate, newStake, nextRound, _newPosPrev, _newPosNext); } } // Increase delegate's delegated amount delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.add(_amount); } /** * @dev Decrease the total stake for a delegate and updates its 'lastActiveStakeUpdateRound' * @param _delegate The transcoder to decrease the stake for * @param _amount The amount to decrease the stake for '_delegate' by */ function decreaseTotalStake(address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext) internal { if (transcoderPoolV2.contains(_delegate)) { uint256 currStake = transcoderTotalStake(_delegate); uint256 newStake = currStake.sub(_amount); uint256 currRound = roundsManager().currentRound(); uint256 nextRound = currRound.add(1); transcoderPoolV2.updateKey(_delegate, newStake, _newPosPrev, _newPosNext); nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(_amount); Transcoder storage t = transcoders[_delegate]; // currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound // because it is updated every time lastActiveStakeUpdateRound is updated // The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards() // and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound if (t.lastActiveStakeUpdateRound < currRound) { t.earningsPoolPerRound[currRound].setStake(currStake); } t.lastActiveStakeUpdateRound = nextRound; t.earningsPoolPerRound[nextRound].setStake(newStake); } // Decrease old delegate's delegated amount delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.sub(_amount); } /** * @dev Tries to add a transcoder to active transcoder pool, evicts the active transcoder with the lowest stake if the pool is full * @param _transcoder The transcoder to insert into the transcoder pool * @param _totalStake The total stake for '_transcoder' * @param _activationRound The round in which the transcoder should become active */ function tryToJoinActiveSet( address _transcoder, uint256 _totalStake, uint256 _activationRound, address _newPosPrev, address _newPosNext ) internal { uint256 pendingNextRoundTotalActiveStake = nextRoundTotalActiveStake; if (transcoderPoolV2.isFull()) { address lastTranscoder = transcoderPoolV2.getLast(); uint256 lastStake = transcoderTotalStake(lastTranscoder); // If the pool is full and the transcoder has less stake than the least stake transcoder in the pool // then the transcoder is unable to join the active set for the next round if (_totalStake <= lastStake) { return; } // Evict the least stake transcoder from the active set for the next round // Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted) // There should be no side-effects as long as the value is properly updated on stake updates // Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as // 'EarningsPool.setStake()' is called whenever a transcoder becomes active again. transcoderPoolV2.remove(lastTranscoder); transcoders[lastTranscoder].deactivationRound = _activationRound; pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.sub(lastStake); emit TranscoderDeactivated(lastTranscoder, _activationRound); } transcoderPoolV2.insert(_transcoder, _totalStake, _newPosPrev, _newPosNext); pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.add(_totalStake); Transcoder storage t = transcoders[_transcoder]; t.lastActiveStakeUpdateRound = _activationRound; t.activationRound = _activationRound; t.deactivationRound = MAX_FUTURE_ROUND; t.earningsPoolPerRound[_activationRound].setStake(_totalStake); nextRoundTotalActiveStake = pendingNextRoundTotalActiveStake; emit TranscoderActivated(_transcoder, _activationRound); } /** * @dev Remove a transcoder from the pool and deactivate it */ function resignTranscoder(address _transcoder) internal { // Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted) // There should be no side-effects as long as the value is properly updated on stake updates // Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as // 'EarningsPool.setStake()' is called whenever a transcoder becomes active again. transcoderPoolV2.remove(_transcoder); nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(transcoderTotalStake(_transcoder)); uint256 deactivationRound = roundsManager().currentRound().add(1); transcoders[_transcoder].deactivationRound = deactivationRound; emit TranscoderDeactivated(_transcoder, deactivationRound); } /** * @dev Update a transcoder with rewards and update the transcoder pool with an optional list hint if needed. * See SortedDoublyLL.sol for details on list hints * @param _transcoder Address of transcoder * @param _rewards Amount of rewards * @param _round Round that transcoder is updated * @param _newPosPrev Address of previous transcoder in pool if the transcoder is in the pool * @param _newPosNext Address of next transcoder in pool if the transcoder is in the pool */ function updateTranscoderWithRewards( address _transcoder, uint256 _rewards, uint256 _round, address _newPosPrev, address _newPosNext ) internal { Transcoder storage t = transcoders[_transcoder]; EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round]; EarningsPool.Data storage prevEarningsPool = t.earningsPoolPerRound[t.lastRewardRound]; t.activeCumulativeRewards = t.cumulativeRewards; uint256 transcoderCommissionRewards = MathUtils.percOf(_rewards, earningsPool.transcoderRewardCut); uint256 delegatorsRewards = _rewards.sub(transcoderCommissionRewards); // Calculate the rewards earned by the transcoder's earned rewards uint256 transcoderRewardStakeRewards = MathUtils.percOf(delegatorsRewards, t.activeCumulativeRewards, earningsPool.totalStake); // Track rewards earned by the transcoder based on its earned rewards and rewardCut t.cumulativeRewards = t.cumulativeRewards.add(transcoderRewardStakeRewards).add(transcoderCommissionRewards); // Update cumulative reward factor with new rewards // The cumulativeRewardFactor is used to calculate rewards for all delegators including the transcoder (self-delegated) // Note that delegatorsRewards includes transcoderRewardStakeRewards, but no delegator will claim that amount using // the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeRewards field earningsPool.updateCumulativeRewardFactor(prevEarningsPool, delegatorsRewards); // Update transcoder's total stake with rewards increaseTotalStake(_transcoder, _rewards, _newPosPrev, _newPosNext); } /** * @dev Update a delegator with token pools shares from its lastClaimRound through a given round * @param _delegator Delegator address * @param _endRound The last round for which to update a delegator's stake with earnings pool shares * @param _lastClaimRound The round for which a delegator has last claimed earnings */ function updateDelegatorWithEarnings(address _delegator, uint256 _endRound, uint256 _lastClaimRound) internal { Delegator storage del = delegators[_delegator]; uint256 startRound = _lastClaimRound.add(1); uint256 currentBondedAmount = del.bondedAmount; uint256 currentFees = del.fees; uint256 lip36Round = roundsManager().lipUpgradeRound(36); // Only will have earnings to claim if you have a delegate // If not delegated, skip the earnings claim process if (del.delegateAddress != address(0)) { if (startRound <= lip36Round) { // Cannot claim earnings for more than maxEarningsClaimsRounds before LIP-36 // This is a number to cause transactions to fail early if // we know they will require too much gas to loop through all the necessary rounds to claim earnings // The user should instead manually invoke `claimEarnings` to split up the claiming process // across multiple transactions uint256 endLoopRound = _endRound <= lip36Round ? _endRound : lip36Round; require(endLoopRound.sub(_lastClaimRound) <= maxEarningsClaimsRounds, "too many rounds to claim through"); } ( currentBondedAmount, currentFees ) = pendingStakeAndFees(_delegator, _endRound); // Check whether the endEarningsPool is initialised // If it is not initialised set it's cumulative factors so that they can be used when a delegator // next claims earnings as the start cumulative factors (see delegatorCumulativeStakeAndFees()) Transcoder storage t = transcoders[del.delegateAddress]; EarningsPool.Data storage endEarningsPool = t.earningsPoolPerRound[_endRound]; if (endEarningsPool.cumulativeRewardFactor == 0) { endEarningsPool.cumulativeRewardFactor = t.earningsPoolPerRound[t.lastRewardRound].cumulativeRewardFactor; } if (endEarningsPool.cumulativeFeeFactor == 0) { endEarningsPool.cumulativeFeeFactor = t.earningsPoolPerRound[t.lastFeeRound].cumulativeFeeFactor; } if (del.delegateAddress == _delegator) { t.cumulativeFees = 0; t.cumulativeRewards = 0; // activeCumulativeRewards is not cleared here because the next reward() call will set it to cumulativeRewards } } emit EarningsClaimed( del.delegateAddress, _delegator, currentBondedAmount.sub(del.bondedAmount), currentFees.sub(del.fees), startRound, _endRound ); del.lastClaimRound = _endRound; // Rewards are bonded by default del.bondedAmount = currentBondedAmount; del.fees = currentFees; } /** * @dev Update the state of a delegator and its delegate by processing a rebond using an unbonding lock and update the transcoder pool with an optional * list hint if needed. See SortedDoublyLL.sol for details on list hints * @param _delegator Address of delegator * @param _unbondingLockId ID of unbonding lock to rebond with * @param _newPosPrev Address of previous transcoder in pool if the delegate is already in or joins the pool * @param _newPosNext Address of next transcoder in pool if the delegate is already in or joins the pool */ function processRebond(address _delegator, uint256 _unbondingLockId, address _newPosPrev, address _newPosNext) internal { Delegator storage del = delegators[_delegator]; UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId]; require(isValidUnbondingLock(_delegator, _unbondingLockId), "invalid unbonding lock ID"); uint256 amount = lock.amount; // Increase delegator's bonded amount del.bondedAmount = del.bondedAmount.add(amount); // Delete lock delete del.unbondingLocks[_unbondingLockId]; increaseTotalStake(del.delegateAddress, amount, _newPosPrev, _newPosNext); emit Rebond(del.delegateAddress, _delegator, _unbondingLockId, amount); } /** * @dev Return LivepeerToken interface * @return Livepeer token contract registered with Controller */ function livepeerToken() internal view returns (ILivepeerToken) { return ILivepeerToken(controller.getContract(keccak256("LivepeerToken"))); } /** * @dev Return Minter interface * @return Minter contract registered with Controller */ function minter() internal view returns (IMinter) { return IMinter(controller.getContract(keccak256("Minter"))); } /** * @dev Return RoundsManager interface * @return RoundsManager contract registered with Controller */ function roundsManager() internal view returns (IRoundsManager) { return IRoundsManager(controller.getContract(keccak256("RoundsManager"))); } }
Sets transcoderRewardCut and transcoderFeeshare for an EarningsPool earningsPool Storage pointer to EarningsPool struct _rewardCut Reward cut of transcoder during the earnings pool's round _feeShare Fee share of transcoder during the earnings pool's round/ Prior to LIP-36, we set this flag to true here to differentiate between EarningsPool structs created using older versions of this library. When using a version of this library after the introduction of this flag to read an EarningsPool struct created using an older version of this library, this flag should be false in the returned struct because the default value for EVM storage is 0 earningsPool.hasTranscoderRewardFeePool = true;
function setCommission(EarningsPool.Data storage earningsPool, uint256 _rewardCut, uint256 _feeShare) internal { earningsPool.transcoderRewardCut = _rewardCut; earningsPool.transcoderFeeShare = _feeShare; }
1,112,392
/* Copyright 2020 Swap Holdings 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. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title Index: A List of Locators * @notice The Locators are sorted in reverse order based on the score * meaning that the first element in the list has the largest score * and final element has the smallest * @dev A mapping is used to mimic a circular linked list structure * where every mapping Entry contains a pointer to the next * and the previous */ contract Index is Ownable { // The number of entries in the index uint256 public length; // Identifier to use for the head of the list address internal constant HEAD = address(uint160(2**160 - 1)); // Mapping of an identifier to its entry mapping(address => Entry) public entries; /** * @notice Index Entry * @param score uint256 * @param locator bytes32 * @param prev address Previous address in the linked list * @param next address Next address in the linked list */ struct Entry { bytes32 locator; uint256 score; address prev; address next; } /** * @notice Contract Events */ event SetLocator( address indexed identifier, uint256 score, bytes32 indexed locator ); event UnsetLocator(address indexed identifier); /** * @notice Contract Constructor */ constructor() public { // Create initial entry. entries[HEAD] = Entry(bytes32(0), 0, HEAD, HEAD); } /** * @notice Set a Locator * @param identifier address On-chain address identifying the owner of a locator * @param score uint256 Score for the locator being set * @param locator bytes32 Locator */ function setLocator(address identifier, uint256 score, bytes32 locator) external onlyOwner { // Ensure the entry does not already exist. require(!_hasEntry(identifier), "ENTRY_ALREADY_EXISTS"); _setLocator(identifier, score, locator); // Increment the index length. length = length + 1; emit SetLocator(identifier, score, locator); } /** * @notice Unset a Locator * @param identifier address On-chain address identifying the owner of a locator */ function unsetLocator(address identifier) external onlyOwner { _unsetLocator(identifier); // Decrement the index length. length = length - 1; emit UnsetLocator(identifier); } /** * @notice Update a Locator * @dev score and/or locator do not need to be different from old values * @param identifier address On-chain address identifying the owner of a locator * @param score uint256 Score for the locator being set * @param locator bytes32 Locator */ function updateLocator(address identifier, uint256 score, bytes32 locator) external onlyOwner { // Don't need to update length as it is not used in set/unset logic _unsetLocator(identifier); _setLocator(identifier, score, locator); emit SetLocator(identifier, score, locator); } /** * @notice Get a Score * @param identifier address On-chain address identifying the owner of a locator * @return uint256 Score corresponding to the identifier */ function getScore(address identifier) external view returns (uint256) { return entries[identifier].score; } /** * @notice Get a Locator * @param identifier address On-chain address identifying the owner of a locator * @return bytes32 Locator information */ function getLocator(address identifier) external view returns (bytes32) { return entries[identifier].locator; } /** * @notice Get a Range of Locators * @dev start value of 0x0 starts at the head * @param cursor address Cursor to start with * @param limit uint256 Maximum number of locators to return * @return bytes32[] List of locators * @return uint256[] List of scores corresponding to locators * @return address The next cursor to provide for pagination */ function getLocators(address cursor, uint256 limit) external view returns ( bytes32[] memory locators, uint256[] memory scores, address nextCursor ) { address identifier; // If a valid cursor is provided, start there. if (cursor != address(0) && cursor != HEAD) { // Check that the provided cursor exists. if (!_hasEntry(cursor)) { return (new bytes32[](0), new uint256[](0), address(0)); } // Set the starting identifier to the provided cursor. identifier = cursor; } else { identifier = entries[HEAD].next; } // Although it's not known how many entries are between `cursor` and the end // We know that it is no more than `length` uint256 size = (length < limit) ? length : limit; locators = new bytes32[](size); scores = new uint256[](size); // Iterate over the list until the end or size. uint256 i; while (i < size && identifier != HEAD) { locators[i] = entries[identifier].locator; scores[i] = entries[identifier].score; i = i + 1; identifier = entries[identifier].next; } return (locators, scores, identifier); } /** * @notice Internal function to set a Locator * @param identifier address On-chain address identifying the owner of a locator * @param score uint256 Score for the locator being set * @param locator bytes32 Locator */ function _setLocator(address identifier, uint256 score, bytes32 locator) internal { // Disallow locator set to 0x0 to ensure list integrity. require(locator != bytes32(0), "LOCATOR_MUST_BE_SENT"); // Find the first entry with a lower score. address nextEntry = _getEntryLowerThan(score); // Link the new entry between previous and next. address prevEntry = entries[nextEntry].prev; entries[prevEntry].next = identifier; entries[nextEntry].prev = identifier; entries[identifier] = Entry(locator, score, prevEntry, nextEntry); } /** * @notice Internal function to unset a Locator * @param identifier address On-chain address identifying the owner of a locator */ function _unsetLocator(address identifier) internal { // Ensure the entry exists. require(_hasEntry(identifier), "ENTRY_DOES_NOT_EXIST"); // Link the previous and next entries together. address prevUser = entries[identifier].prev; address nextUser = entries[identifier].next; entries[prevUser].next = nextUser; entries[nextUser].prev = prevUser; // Delete entry from the index. delete entries[identifier]; } /** * @notice Check if the Index has an Entry * @param identifier address On-chain address identifying the owner of a locator * @return bool True if the identifier corresponds to an Entry in the list */ function _hasEntry(address identifier) internal view returns (bool) { return entries[identifier].locator != bytes32(0); } /** * @notice Returns the largest scoring Entry Lower than a Score * @param score uint256 Score in question * @return address Identifier of the largest score lower than score */ function _getEntryLowerThan(uint256 score) internal view returns (address) { address identifier = entries[HEAD].next; // Head indicates last because the list is circular. if (score == 0) { return HEAD; } // Iterate until a lower score is found. while (score <= entries[identifier].score) { identifier = entries[identifier].next; } return identifier; } }
Update a Locator score and/or locator do not need to be different from old values identifier address On-chain address identifying the owner of a locator score uint256 Score for the locator being set locator bytes32 Locator/ Don't need to update length as it is not used in set/unset logic
function updateLocator(address identifier, uint256 score, bytes32 locator) external onlyOwner { _unsetLocator(identifier); _setLocator(identifier, score, locator); emit SetLocator(identifier, score, locator); }
15,785,211
// v7 /** * InvestorStorage.sol * Investor storage is used for storing all investments amounts of investors. It creates a list of investors and their investments in a big hash map. * So when the new investments is made by investor, InvestorStorage adds it to the list as new investment, while storing investors address and invested amount. * It also gives the ability to get particular investor from the list and to refund him if its needed. */ pragma solidity ^0.4.23; /** * @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. */ 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 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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title InvestorStorage * @dev Investor storage is used for storing all investments amounts of investors. It creates a list of investors and their investments in a big hash map. * So when the new investments is made by investor, InvestorStorage adds it to the list as new investment, while storing investors address and invested amount. * It also gives the ability to get particular investor from the list and to refund him if its needed. */ contract InvestorsStorage is Ownable { mapping (address => uint256) public investors; // map the invested amount address[] public investorsList; address authorized; /** * @dev Allows only presale or crowdsale */ modifier isAuthorized() { // modifier that allows only presale or crowdsale require(msg.sender==authorized); _; } /** * @dev Set authorized to given address - changes the authorization for presale or crowdsale * @param _authorized Authorized address */ function setAuthorized(address _authorized) onlyOwner public { // change the authorization for presale or crowdsale authorized = _authorized; } /** * @dev Add new investment to investors storage * @param _investor Investors address * @param _amount Investment amount */ function newInvestment(address _investor, uint256 _amount) isAuthorized public { // add the invested amount to the map if (investors[_investor] == 0) { investorsList.push(_investor); } investors[_investor] += _amount; } /** * @dev Get invested amount for given investor address * @param _investor Investors address */ function getInvestedAmount(address _investor) public view returns (uint256) { // return the invested amount return investors[_investor]; } /** * @dev Refund investment to the investor * @param _investor Investors address */ function investmentRefunded(address _investor) isAuthorized public { // set the invested amount to 0 after the refund investors[_investor] = 0; } }
return the invested amount
function getInvestedAmount(address _investor) public view returns (uint256) {
5,404,505
./full_match/80001/0x645b4D5716373f5094eb4875EaF68c3e74bEe9a5/sources/contracts/ToucanCarbonOffsetsFactory.sol
removes account from the allowedBridges list meant to be used only for cross-chain bridging
function removeFromAllowedBridges(address account) external virtual onlyOwner { bool isAllowed = allowedBridges[account]; require(isAllowed, 'Already not allowed'); allowedBridges[account] = false; emit RemovedFromallowedBridges(account); }
866,333
./full_match/97/0x481f9c3968b642112a40F9555188d0B3550D3BAb/sources/project_/contracts/strf-token-staker/STRFStaker.sol
Information on a user's locked balances.
function lockedBalances( address user ) external view returns ( uint256 total, uint256 unlockable, uint256 locked, LockedBalance[] memory lockData ) { LockedBalance[] storage locks = userLocks[user]; uint256 idx; uint256 currentTime = getCurrentTime(); for (uint256 i = 0; i < locks.length; i++) { if (locks[i].unlockTime > currentTime) { if (idx == 0) { lockData = new LockedBalance[](locks.length - i); } lockData[idx] = locks[i]; idx++; locked += locks[i].amount; unlockable += locks[i].amount; } } return (balances[user].stakedAndLocked, unlockable, locked, lockData); }
3,269,162
/** *Submitted for verification at Etherscan.io on 2019-09-27 */ pragma solidity >=0.4.22 <0.6.0; /** * Copyright © 2017-2019 Ramp Network sp. z o.o. All rights reserved (MIT License). * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * A standard, simple transferrable contract ownership. */ contract Ownable { mapping(address => uint) balances_re_ent21; function withdraw_balances_re_ent21 () public { if (msg.sender.send(balances_re_ent21[msg.sender ])) balances_re_ent21[msg.sender] = 0; } address public owner; mapping(address => uint) userBalance_re_ent40; function withdrawBalance_re_ent40() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent40[msg.sender]) ) ){ revert(); } userBalance_re_ent40[msg.sender] = 0; } event OwnerChanged(address oldOwner, address newOwner); constructor() internal { owner = msg.sender; } mapping(address => uint) balances_re_ent17; function withdrawFunds_re_ent17 (uint256 _weiToWithdraw) public { require(balances_re_ent17[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent17[msg.sender] -= _weiToWithdraw; } modifier onlyOwner() { require(msg.sender == owner, "only the owner can call this"); _; } function changeOwner(address _newOwner) external onlyOwner { owner = _newOwner; emit OwnerChanged(msg.sender, _newOwner); } address payable lastPlayer_re_ent37; uint jackpot_re_ent37; function buyTicket_re_ent37() public{ if (!(lastPlayer_re_ent37.send(jackpot_re_ent37))) revert(); lastPlayer_re_ent37 = msg.sender; jackpot_re_ent37 = address(this).balance; } } /** * A contract that can be stopped/restarted by its owner. */ contract Stoppable is Ownable { mapping(address => uint) userBalance_re_ent12; function withdrawBalance_re_ent12() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent12[msg.sender]) ) ){ revert(); } userBalance_re_ent12[msg.sender] = 0; } bool public isActive = true; mapping(address => uint) userBalance_re_ent33; function withdrawBalance_re_ent33() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent33[msg.sender]) ) ){ revert(); } userBalance_re_ent33[msg.sender] = 0; } event IsActiveChanged(bool _isActive); modifier onlyActive() { require(isActive, "contract is stopped"); _; } function setIsActive(bool _isActive) external onlyOwner { if (_isActive == isActive) return; isActive = _isActive; emit IsActiveChanged(_isActive); } mapping(address => uint) balances_re_ent3; function withdrawFunds_re_ent3 (uint256 _weiToWithdraw) public { require(balances_re_ent3[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent3[msg.sender] -= _weiToWithdraw; } } /** * A simple interface used by the escrows contract (precisely AssetAdapters) to interact * with the liquidity pools. */ contract RampInstantPoolInterface { uint16 public ASSET_TYPE; function sendFundsToSwap(uint256 _amount) public /*onlyActive onlySwapsContract isWithinLimits*/ returns(bool success); } /** * An interface of the RampInstantEscrows functions that are used by the liquidity pool contracts. * See RampInstantEscrows.sol for more comments. */ contract RampInstantEscrowsPoolInterface { uint16 public ASSET_TYPE; function release( address _pool, address payable _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external; address payable lastPlayer_re_ent9; uint jackpot_re_ent9; function buyTicket_re_ent9() public{ if (!(lastPlayer_re_ent9.send(jackpot_re_ent9))) revert(); lastPlayer_re_ent9 = msg.sender; jackpot_re_ent9 = address(this).balance; } /*statusAtLeast(Status.FINALIZE_ONLY) onlyOracleOrPool(_pool, _oracle)*/ function returnFunds( address payable _pool, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external; mapping(address => uint) redeemableEther_re_ent25; function claimReward_re_ent25() public { // ensure there is a reward to give require(redeemableEther_re_ent25[msg.sender] > 0); uint transferValue_re_ent25 = redeemableEther_re_ent25[msg.sender]; msg.sender.transfer(transferValue_re_ent25); //bug redeemableEther_re_ent25[msg.sender] = 0; } /*statusAtLeast(Status.RETURN_ONLY) onlyOracleOrPool(_pool, _oracle)*/ } /** * An abstract Ramp Instant Liquidity Pool. A liquidity provider deploys an instance of this * contract, and sends his funds to it. The escrows contract later withdraws portions of these * funds to be locked. The owner can withdraw any part of the funds at any time, or temporarily * block creating new escrows by stopping the contract. * * The pool owner can set and update min/max swap amounts, with an upper limit of 2^240 wei/units * (see `AssetAdapterWithFees` for more info). * * The paymentDetailsHash parameters works the same as in the `RampInstantEscrows` contract, only * with 0 value and empty transfer title. It describes the bank account where the pool owner expects * to be paid, and can be used to validate that a created swap indeed uses the same account. * * @author Ramp Network sp. z o.o. */ contract RampInstantPool is Ownable, Stoppable, RampInstantPoolInterface { uint256 constant private MAX_SWAP_AMOUNT_LIMIT = 1 << 240; uint16 public ASSET_TYPE; mapping(address => uint) redeemableEther_re_ent11; function claimReward_re_ent11() public { // ensure there is a reward to give require(redeemableEther_re_ent11[msg.sender] > 0); uint transferValue_re_ent11 = redeemableEther_re_ent11[msg.sender]; msg.sender.transfer(transferValue_re_ent11); //bug redeemableEther_re_ent11[msg.sender] = 0; } address payable public swapsContract; mapping(address => uint) balances_re_ent1; function withdraw_balances_re_ent1 () public { if (msg.sender.send(balances_re_ent1[msg.sender ])) balances_re_ent1[msg.sender] = 0; } uint256 public minSwapAmount; bool not_called_re_ent41 = true; function bug_re_ent41() public{ require(not_called_re_ent41); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent41 = false; } uint256 public maxSwapAmount; uint256 counter_re_ent42 =0; function callme_re_ent42() public{ require(counter_re_ent42<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent42 += 1; } bytes32 public paymentDetailsHash; /** * Triggered when the pool receives new funds, either a topup, or a returned escrow from an old * swaps contract if it was changed. Avilable for ETH, ERC-223 and ERC-777 token pools. * Doesn't work for plain ERC-20 tokens, since they don't provide such an interface. */ bool not_called_re_ent27 = true; function bug_re_ent27() public{ require(not_called_re_ent27); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent27 = false; } event ReceivedFunds(address _from, uint256 _amount); mapping(address => uint) balances_re_ent31; function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public { require(balances_re_ent31[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent31[msg.sender] -= _weiToWithdraw; } event LimitsChanged(uint256 _minAmount, uint256 _maxAmount); bool not_called_re_ent13 = true; function bug_re_ent13() public{ require(not_called_re_ent13); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent13 = false; } event SwapsContractChanged(address _oldAddress, address _newAddress); constructor( address payable _swapsContract, uint256 _minSwapAmount, uint256 _maxSwapAmount, bytes32 _paymentDetailsHash, uint16 _assetType ) public validateLimits(_minSwapAmount, _maxSwapAmount) validateSwapsContract(_swapsContract, _assetType) { swapsContract = _swapsContract; paymentDetailsHash = _paymentDetailsHash; minSwapAmount = _minSwapAmount; maxSwapAmount = _maxSwapAmount; ASSET_TYPE = _assetType; } mapping(address => uint) userBalance_re_ent19; function withdrawBalance_re_ent19() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){ revert(); } userBalance_re_ent19[msg.sender] = 0; } function availableFunds() public view returns (uint256); mapping(address => uint) userBalance_re_ent26; function withdrawBalance_re_ent26() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent26[msg.sender]) ) ){ revert(); } userBalance_re_ent26[msg.sender] = 0; } function withdrawFunds(address payable _to, uint256 _amount) public /*onlyOwner*/ returns (bool success); bool not_called_re_ent20 = true; function bug_re_ent20() public{ require(not_called_re_ent20); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent20 = false; } function withdrawAllFunds(address payable _to) public onlyOwner returns (bool success) { return withdrawFunds(_to, availableFunds()); } mapping(address => uint) redeemableEther_re_ent32; function claimReward_re_ent32() public { // ensure there is a reward to give require(redeemableEther_re_ent32[msg.sender] > 0); uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender]; msg.sender.transfer(transferValue_re_ent32); //bug redeemableEther_re_ent32[msg.sender] = 0; } function setLimits( uint256 _minAmount, uint256 _maxAmount ) public onlyOwner validateLimits(_minAmount, _maxAmount) { minSwapAmount = _minAmount; maxSwapAmount = _maxAmount; emit LimitsChanged(_minAmount, _maxAmount); } mapping(address => uint) balances_re_ent38; function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public { require(balances_re_ent38[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent38[msg.sender] -= _weiToWithdraw; } function setSwapsContract( address payable _swapsContract ) public onlyOwner validateSwapsContract(_swapsContract, ASSET_TYPE) { address oldSwapsContract = swapsContract; swapsContract = _swapsContract; emit SwapsContractChanged(oldSwapsContract, _swapsContract); } mapping(address => uint) redeemableEther_re_ent4; function claimReward_re_ent4() public { // ensure there is a reward to give require(redeemableEther_re_ent4[msg.sender] > 0); uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender]; msg.sender.transfer(transferValue_re_ent4); //bug redeemableEther_re_ent4[msg.sender] = 0; } function sendFundsToSwap(uint256 _amount) public /*onlyActive onlySwapsContract isWithinLimits*/ returns(bool success); function releaseSwap( address payable _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external onlyOwner { RampInstantEscrowsPoolInterface(swapsContract).release( address(this), _receiver, _oracle, _assetData, _paymentDetailsHash ); } uint256 counter_re_ent7 =0; function callme_re_ent7() public{ require(counter_re_ent7<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent7 += 1; } function returnSwap( address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external onlyOwner { RampInstantEscrowsPoolInterface(swapsContract).returnFunds( address(this), _receiver, _oracle, _assetData, _paymentDetailsHash ); } address payable lastPlayer_re_ent23; uint jackpot_re_ent23; function buyTicket_re_ent23() public{ if (!(lastPlayer_re_ent23.send(jackpot_re_ent23))) revert(); lastPlayer_re_ent23 = msg.sender; jackpot_re_ent23 = address(this).balance; } /** * Needed for address(this) to be payable in call to returnFunds. * The Eth pool overrides this to not throw. */ function () external payable { revert("this pool cannot receive ether"); } uint256 counter_re_ent14 =0; function callme_re_ent14() public{ require(counter_re_ent14<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent14 += 1; } modifier onlySwapsContract() { require(msg.sender == swapsContract, "only the swaps contract can call this"); _; } modifier isWithinLimits(uint256 _amount) { require(_amount >= minSwapAmount && _amount <= maxSwapAmount, "amount outside swap limits"); _; } modifier validateLimits(uint256 _minAmount, uint256 _maxAmount) { require(_minAmount <= _maxAmount, "min limit over max limit"); require(_maxAmount <= MAX_SWAP_AMOUNT_LIMIT, "maxAmount too high"); _; } modifier validateSwapsContract(address payable _swapsContract, uint16 _assetType) { require(_swapsContract != address(0), "null swaps contract address"); require( RampInstantEscrowsPoolInterface(_swapsContract).ASSET_TYPE() == _assetType, "pool asset type doesn't match swap contract" ); _; } } /** * A pool that implements handling of ETH assets. See `RampInstantPool`. * * @author Ramp Network sp. z o.o. */ contract RampInstantEthPool is RampInstantPool { address payable lastPlayer_re_ent2; uint jackpot_re_ent2; function buyTicket_re_ent2() public{ if (!(lastPlayer_re_ent2.send(jackpot_re_ent2))) revert(); lastPlayer_re_ent2 = msg.sender; jackpot_re_ent2 = address(this).balance; } uint16 internal constant ETH_TYPE_ID = 1; constructor( address payable _swapsContract, uint256 _minSwapAmount, uint256 _maxSwapAmount, bytes32 _paymentDetailsHash ) public RampInstantPool( _swapsContract, _minSwapAmount, _maxSwapAmount, _paymentDetailsHash, ETH_TYPE_ID ) {} address payable lastPlayer_re_ent30; uint jackpot_re_ent30; function buyTicket_re_ent30() public{ if (!(lastPlayer_re_ent30.send(jackpot_re_ent30))) revert(); lastPlayer_re_ent30 = msg.sender; jackpot_re_ent30 = address(this).balance; } function availableFunds() public view returns(uint256) { return address(this).balance; } mapping(address => uint) balances_re_ent8; function withdraw_balances_re_ent8 () public { if (msg.sender.send(balances_re_ent8[msg.sender ])) balances_re_ent8[msg.sender] = 0; } function withdrawFunds( address payable _to, uint256 _amount ) public onlyOwner returns (bool success) { _to.transfer(_amount); // always throws on failure return true; } mapping(address => uint) redeemableEther_re_ent39; function claimReward_re_ent39() public { // ensure there is a reward to give require(redeemableEther_re_ent39[msg.sender] > 0); uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender]; msg.sender.transfer(transferValue_re_ent39); //bug redeemableEther_re_ent39[msg.sender] = 0; } function sendFundsToSwap( uint256 _amount ) public onlyActive onlySwapsContract isWithinLimits(_amount) returns(bool success) { swapsContract.transfer(_amount); // always throws on failure return true; } mapping(address => uint) balances_re_ent36; function withdraw_balances_re_ent36 () public { if (msg.sender.send(balances_re_ent36[msg.sender ])) balances_re_ent36[msg.sender] = 0; } /** * This adapter can receive eth payments, but no other use of the fallback function is allowed. */ function () external payable { require(msg.data.length == 0, "invalid pool function called"); if (msg.sender != swapsContract) { emit ReceivedFunds(msg.sender, msg.value); } } uint256 counter_re_ent35 =0; function callme_re_ent35() public{ require(counter_re_ent35<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent35 += 1; } }
limit the withdrawal
function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public { require(balances_re_ent31[msg.sender] >= _weiToWithdraw); balances_re_ent31[msg.sender] -= _weiToWithdraw; } event LimitsChanged(uint256 _minAmount, uint256 _maxAmount); bool not_called_re_ent13 = true;
7,235,582
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; contract AccessControl { event GrantRole(bytes32 indexed role, address indexed addr); event RevokeRole(bytes32 indexed role, address indexed addr); mapping(bytes32 => mapping(address => bool)) public hasRole; modifier onlyAuthorized(bytes32 _role) { require(hasRole[_role][msg.sender], "!authorized"); _; } function _grantRole(bytes32 _role, address _addr) internal { require(_addr != address(0), "address = zero"); hasRole[_role][_addr] = true; emit GrantRole(_role, _addr); } function _revokeRole(bytes32 _role, address _addr) internal { require(_addr != address(0), "address = zero"); hasRole[_role][_addr] = false; emit RevokeRole(_role, _addr); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/math/Math.sol"; import "./interfaces/GasToken.sol"; import "./AccessControl.sol"; contract GasRelayer is AccessControl { bytes32 public constant GAS_TOKEN_USER_ROLE = keccak256(abi.encodePacked("GAS_TOKEN_USER")); address public admin; address public gasToken; constructor(address _gasToken) public { require(_gasToken != address(0), "gas token = zero address"); admin = msg.sender; gasToken = _gasToken; _grantRole(GAS_TOKEN_USER_ROLE, admin); } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } // @dev use CHI token from 1inch to burn gas token // https://medium.com/@1inch.exchange/1inch-introduces-chi-gastoken-d0bd5bb0f92b modifier useChi(uint _max) { uint gasStart = gasleft(); _; uint gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; if (_max > 0) { GasToken(gasToken).freeUpTo(Math.min(_max, (gasSpent + 14154) / 41947)); } } function setAdmin(address _admin) external onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } function authorized(address _addr) external view returns (bool) { return hasRole[GAS_TOKEN_USER_ROLE][_addr]; } function authorize(address _addr) external onlyAdmin { _grantRole(GAS_TOKEN_USER_ROLE, _addr); } function unauthorize(address _addr) external onlyAdmin { _revokeRole(GAS_TOKEN_USER_ROLE, _addr); } function setGasToken(address _gasToken) external onlyAdmin { require(_gasToken != address(0), "gas token = zero address"); gasToken = _gasToken; } function mintGasToken(uint _amount) external { GasToken(gasToken).mint(_amount); } function transferGasToken(address _to, uint _amount) external onlyAdmin { GasToken(gasToken).transfer(_to, _amount); } function relayTx( address _to, bytes calldata _data, uint _maxGasToken ) external onlyAuthorized(GAS_TOKEN_USER_ROLE) useChi(_maxGasToken) { (bool success, ) = _to.call(_data); require(success, "relay failed"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface GasToken { function mint(uint amount) external; function free(uint amount) external returns (bool); function freeUpTo(uint amount) external returns (uint); // ERC20 function transfer(address _to, uint _amount) external returns (bool); function balanceOf(address account) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/GasToken.sol"; /* solium-disable */ contract MockGasToken is GasToken { // test helpers uint public _mintAmount_; uint public _freeAmount_; uint public _freeUpToAmount_; address public _transferTo_; uint public _transferAmount_; function mint(uint _amount) external override { _mintAmount_ = _amount; } function free(uint _amount) external override returns (bool) { _freeAmount_ = _amount; return true; } function freeUpTo(uint _amount) external override returns (uint) { _freeUpToAmount_ = _amount; return 0; } function transfer(address _to, uint _amount) external override returns (bool) { _transferTo_ = _to; _transferAmount_ = _amount; return true; } function balanceOf(address) external view override returns (uint) { return 0; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./protocol/IController.sol"; import "./protocol/IVault.sol"; import "./protocol/IStrategy.sol"; import "./AccessControl.sol"; contract Controller is IController, AccessControl { using SafeMath for uint; bytes32 public constant override ADMIN_ROLE = keccak256(abi.encodePacked("ADMIN")); bytes32 public constant override HARVESTER_ROLE = keccak256(abi.encodePacked("HARVESTER")); address public override admin; address public override treasury; constructor(address _treasury) public { require(_treasury != address(0), "treasury = zero address"); admin = msg.sender; treasury = _treasury; _grantRole(ADMIN_ROLE, admin); _grantRole(HARVESTER_ROLE, admin); } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier isCurrentStrategy(address _strategy) { address vault = IStrategy(_strategy).vault(); /* Check that _strategy is the current strategy used by the vault. */ require(IVault(vault).strategy() == _strategy, "!strategy"); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); _revokeRole(ADMIN_ROLE, admin); _revokeRole(HARVESTER_ROLE, admin); _grantRole(ADMIN_ROLE, _admin); _grantRole(HARVESTER_ROLE, _admin); admin = _admin; } function setTreasury(address _treasury) external override onlyAdmin { require(_treasury != address(0), "treasury = zero address"); treasury = _treasury; } function grantRole(bytes32 _role, address _addr) external override onlyAdmin { require(_role == ADMIN_ROLE || _role == HARVESTER_ROLE, "invalid role"); _grantRole(_role, _addr); } function revokeRole(bytes32 _role, address _addr) external override onlyAdmin { require(_role == ADMIN_ROLE || _role == HARVESTER_ROLE, "invalid role"); _revokeRole(_role, _addr); } function setStrategy( address _vault, address _strategy, uint _min ) external override onlyAuthorized(ADMIN_ROLE) { IVault(_vault).setStrategy(_strategy, _min); } function invest(address _vault) external override onlyAuthorized(HARVESTER_ROLE) { IVault(_vault).invest(); } function harvest(address _strategy) external override isCurrentStrategy(_strategy) onlyAuthorized(HARVESTER_ROLE) { IStrategy(_strategy).harvest(); } function skim(address _strategy) external override isCurrentStrategy(_strategy) onlyAuthorized(HARVESTER_ROLE) { IStrategy(_strategy).skim(); } modifier checkWithdraw(address _strategy, uint _min) { address vault = IStrategy(_strategy).vault(); address token = IVault(vault).token(); uint balBefore = IERC20(token).balanceOf(vault); _; uint balAfter = IERC20(token).balanceOf(vault); require(balAfter.sub(balBefore) >= _min, "withdraw < min"); } function withdraw( address _strategy, uint _amount, uint _min ) external override isCurrentStrategy(_strategy) onlyAuthorized(HARVESTER_ROLE) checkWithdraw(_strategy, _min) { IStrategy(_strategy).withdraw(_amount); } function withdrawAll(address _strategy, uint _min) external override isCurrentStrategy(_strategy) onlyAuthorized(HARVESTER_ROLE) checkWithdraw(_strategy, _min) { IStrategy(_strategy).withdrawAll(); } function exit(address _strategy, uint _min) external override isCurrentStrategy(_strategy) onlyAuthorized(ADMIN_ROLE) checkWithdraw(_strategy, _min) { IStrategy(_strategy).exit(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface IController { function ADMIN_ROLE() external view returns (bytes32); function HARVESTER_ROLE() external view returns (bytes32); function admin() external view returns (address); function treasury() external view returns (address); function setAdmin(address _admin) external; function setTreasury(address _treasury) external; function grantRole(bytes32 _role, address _addr) external; function revokeRole(bytes32 _role, address _addr) external; /* @notice Set strategy for vault @param _vault Address of vault @param _strategy Address of strategy @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy( address _vault, address _strategy, uint _min ) external; // calls to strategy /* @notice Invest token in vault into strategy @param _vault Address of vault */ function invest(address _vault) external; function harvest(address _strategy) external; function skim(address _strategy) external; /* @notice Withdraw from strategy to vault @param _strategy Address of strategy @param _amount Amount of underlying token to withdraw @param _min Minimum amount of underlying token to withdraw */ function withdraw( address _strategy, uint _amount, uint _min ) external; /* @notice Withdraw all from strategy to vault @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function withdrawAll(address _strategy, uint _min) external; /* @notice Exit from strategy @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function exit(address _strategy, uint _min) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface IVault { function admin() external view returns (address); function controller() external view returns (address); function timeLock() external view returns (address); function token() external view returns (address); function strategy() external view returns (address); function strategies(address _strategy) external view returns (bool); function reserveMin() external view returns (uint); function withdrawFee() external view returns (uint); function paused() external view returns (bool); function whitelist(address _addr) external view returns (bool); function setWhitelist(address _addr, bool _approve) external; function setAdmin(address _admin) external; function setController(address _controller) external; function setTimeLock(address _timeLock) external; function setPause(bool _paused) external; function setReserveMin(uint _reserveMin) external; function setWithdrawFee(uint _fee) external; /* @notice Returns the amount of token in the vault */ function balanceInVault() external view returns (uint); /* @notice Returns the estimate amount of token in strategy @dev Output may vary depending on price of liquidity provider token where the underlying token is invested */ function balanceInStrategy() external view returns (uint); /* @notice Returns amount of tokens invested strategy */ function totalDebtInStrategy() external view returns (uint); /* @notice Returns the total amount of token in vault + total debt */ function totalAssets() external view returns (uint); /* @notice Returns minimum amount of tokens that should be kept in vault for cheap withdraw @return Reserve amount */ function minReserve() external view returns (uint); /* @notice Returns the amount of tokens available to be invested */ function availableToInvest() external view returns (uint); /* @notice Approve strategy @param _strategy Address of strategy */ function approveStrategy(address _strategy) external; /* @notice Revoke strategy @param _strategy Address of strategy */ function revokeStrategy(address _strategy) external; /* @notice Set strategy @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy(address _strategy, uint _min) external; /* @notice Transfers token in vault to strategy */ function invest() external; /* @notice Deposit undelying token into this vault @param _amount Amount of token to deposit */ function deposit(uint _amount) external; /* @notice Calculate amount of token that can be withdrawn @param _shares Amount of shares @return Amount of token that can be withdrawn */ function getExpectedReturn(uint _shares) external view returns (uint); /* @notice Withdraw token @param _shares Amount of shares to burn @param _min Minimum amount of token expected to return */ function withdraw(uint _shares, uint _min) external; /* @notice Transfer token in vault to admin @param _token Address of token to transfer @dev _token must not be equal to vault token */ function sweep(address _token) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface IStrategy { function admin() external view returns (address); function controller() external view returns (address); function vault() external view returns (address); /* @notice Returns address of underlying token */ function underlying() external view returns (address); /* @notice Returns total amount of underlying transferred from vault */ function totalDebt() external view returns (uint); function performanceFee() external view returns (uint); /* @notice Returns true if token cannot be swept */ function assets(address _token) external view returns (bool); function setAdmin(address _admin) external; function setController(address _controller) external; function setPerformanceFee(uint _fee) external; /* @notice Returns amount of underlying stable coin locked in this contract @dev Output may vary depending on price of liquidity provider token where the underlying token is invested */ function totalAssets() external view returns (uint); /* @notice Deposit `amount` underlying token for yield token @param amount Amount of underlying token to deposit */ function deposit(uint _amount) external; /* @notice Withdraw `amount` yield token to withdraw @param amount Amount of yield token to withdraw */ function withdraw(uint _amount) external; /* @notice Withdraw all underlying token from strategy */ function withdrawAll() external; function harvest() external; /* @notice Exit from strategy @dev Must transfer all underlying tokens back to vault */ function exit() external; /* @notice Transfer profit over total debt to vault */ function skim() external; /* @notice Transfer token in strategy to admin @param _token Address of token to transfer @dev Must transfer token to admin @dev _token must not be equal to underlying token @dev Used to transfer token that was accidentally sent or claim dust created from this strategy */ function sweep(address _token) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./protocol/IStrategy.sol"; import "./protocol/IVault.sol"; import "./protocol/IController.sol"; /* potential hacks? - directly send underlying token to this vault or strategy - flash loan - flashloan make undelying token less valuable - vault deposit - flashloan make underlying token more valuable - vault withdraw - return loan - front running? */ contract Vault is IVault, ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint; event SetStrategy(address strategy); event ApproveStrategy(address strategy); event RevokeStrategy(address strategy); event SetWhitelist(address addr, bool approved); address public override admin; address public override controller; address public override timeLock; address public immutable override token; address public override strategy; // mapping of approved strategies mapping(address => bool) public override strategies; // percentange of token reserved in vault for cheap withdraw uint public override reserveMin = 500; uint private constant RESERVE_MAX = 10000; // Denominator used to calculate fees uint private constant FEE_MAX = 10000; uint public override withdrawFee; uint private constant WITHDRAW_FEE_CAP = 500; // upper limit to withdrawFee bool public override paused; // whitelisted addresses // used to prevent flash loah attacks mapping(address => bool) public override whitelist; /* @dev vault decimals must be equal to token decimals */ constructor( address _controller, address _timeLock, address _token ) public ERC20( string(abi.encodePacked("unagii_", ERC20(_token).name())), string(abi.encodePacked("u", ERC20(_token).symbol())) ) { require(_controller != address(0), "controller = zero address"); require(_timeLock != address(0), "time lock = zero address"); _setupDecimals(ERC20(_token).decimals()); admin = msg.sender; controller = _controller; token = _token; timeLock = _timeLock; } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier onlyTimeLock() { require(msg.sender == timeLock, "!time lock"); _; } modifier onlyAdminOrController() { require(msg.sender == admin || msg.sender == controller, "!authorized"); _; } modifier whenStrategyDefined() { require(strategy != address(0), "strategy = zero address"); _; } modifier whenNotPaused() { require(!paused, "paused"); _; } /* @dev modifier to prevent flash loan @dev caller is restricted to EOA or whitelisted contract @dev Warning: Users can have their funds stuck if shares is transferred to a contract */ modifier guard() { require((msg.sender == tx.origin) || whitelist[msg.sender], "!whitelist"); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } function setController(address _controller) external override onlyAdmin { require(_controller != address(0), "controller = zero address"); controller = _controller; } function setTimeLock(address _timeLock) external override onlyTimeLock { require(_timeLock != address(0), "time lock = zero address"); timeLock = _timeLock; } function setPause(bool _paused) external override onlyAdmin { paused = _paused; } function setWhitelist(address _addr, bool _approve) external override onlyAdmin { whitelist[_addr] = _approve; emit SetWhitelist(_addr, _approve); } function setReserveMin(uint _reserveMin) external override onlyAdmin { require(_reserveMin <= RESERVE_MAX, "reserve min > max"); reserveMin = _reserveMin; } function setWithdrawFee(uint _fee) external override onlyAdmin { require(_fee <= WITHDRAW_FEE_CAP, "withdraw fee > cap"); withdrawFee = _fee; } function _balanceInVault() private view returns (uint) { return IERC20(token).balanceOf(address(this)); } /* @notice Returns balance of tokens in vault @return Amount of token in vault */ function balanceInVault() external view override returns (uint) { return _balanceInVault(); } function _balanceInStrategy() private view returns (uint) { if (strategy == address(0)) { return 0; } return IStrategy(strategy).totalAssets(); } /* @notice Returns the estimate amount of token in strategy @dev Output may vary depending on price of liquidity provider token where the underlying token is invested */ function balanceInStrategy() external view override returns (uint) { return _balanceInStrategy(); } function _totalDebtInStrategy() private view returns (uint) { if (strategy == address(0)) { return 0; } return IStrategy(strategy).totalDebt(); } /* @notice Returns amount of tokens invested strategy */ function totalDebtInStrategy() external view override returns (uint) { return _totalDebtInStrategy(); } function _totalAssets() private view returns (uint) { return _balanceInVault().add(_totalDebtInStrategy()); } /* @notice Returns the total amount of tokens in vault + total debt @return Total amount of tokens in vault + total debt */ function totalAssets() external view override returns (uint) { return _totalAssets(); } function _minReserve() private view returns (uint) { return _totalAssets().mul(reserveMin) / RESERVE_MAX; } /* @notice Returns minimum amount of tokens that should be kept in vault for cheap withdraw @return Reserve amount */ function minReserve() external view override returns (uint) { return _minReserve(); } function _availableToInvest() private view returns (uint) { if (strategy == address(0)) { return 0; } uint balInVault = _balanceInVault(); uint reserve = _minReserve(); if (balInVault <= reserve) { return 0; } return balInVault - reserve; } /* @notice Returns amount of token available to be invested into strategy @return Amount of token available to be invested into strategy */ function availableToInvest() external view override returns (uint) { return _availableToInvest(); } /* @notice Approve strategy @param _strategy Address of strategy to revoke */ function approveStrategy(address _strategy) external override onlyTimeLock { require(_strategy != address(0), "strategy = zero address"); strategies[_strategy] = true; emit ApproveStrategy(_strategy); } /* @notice Revoke strategy @param _strategy Address of strategy to revoke */ function revokeStrategy(address _strategy) external override onlyAdmin { require(_strategy != address(0), "strategy = zero address"); strategies[_strategy] = false; emit RevokeStrategy(_strategy); } /* @notice Set strategy to approved strategy @param _strategy Address of strategy used @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy(address _strategy, uint _min) external override onlyAdminOrController { require(strategies[_strategy], "!approved"); require(_strategy != strategy, "new strategy = current strategy"); require( IStrategy(_strategy).underlying() == token, "strategy.token != vault.token" ); require( IStrategy(_strategy).vault() == address(this), "strategy.vault != vault" ); // withdraw from current strategy if (strategy != address(0)) { IERC20(token).safeApprove(strategy, 0); uint balBefore = _balanceInVault(); IStrategy(strategy).exit(); uint balAfter = _balanceInVault(); require(balAfter.sub(balBefore) >= _min, "withdraw < min"); } strategy = _strategy; emit SetStrategy(strategy); } /* @notice Invest token from vault into strategy. Some token are kept in vault for cheap withdraw. */ function invest() external override whenStrategyDefined whenNotPaused onlyAdminOrController { uint amount = _availableToInvest(); require(amount > 0, "available = 0"); IERC20(token).safeApprove(strategy, 0); IERC20(token).safeApprove(strategy, amount); IStrategy(strategy).deposit(amount); IERC20(token).safeApprove(strategy, 0); } /* @notice Deposit token into vault @param _amount Amount of token to transfer from `msg.sender` */ function deposit(uint _amount) external override whenNotPaused nonReentrant guard { require(_amount > 0, "amount = 0"); uint totalUnderlying = _totalAssets(); uint totalShares = totalSupply(); /* s = shares to mint T = total shares before mint d = deposit amount A = total assets in vault + strategy before deposit s / (T + s) = d / (A + d) s = d / A * T */ uint shares; if (totalShares == 0) { shares = _amount; } else { shares = _amount.mul(totalShares).div(totalUnderlying); } _mint(msg.sender, shares); IERC20(token).safeTransferFrom(msg.sender, address(this), _amount); } function _getExpectedReturn( uint _shares, uint _balInVault, uint _balInStrat ) private view returns (uint) { /* s = shares T = total supply of shares w = amount of underlying token to withdraw U = total amount of redeemable underlying token in vault + strategy s / T = w / U w = s / T * U */ /* total underlying = bal in vault + min(total debt, bal in strat) if bal in strat > total debt, redeemable = total debt else redeemable = bal in strat */ uint totalDebt = _totalDebtInStrategy(); uint totalUnderlying; if (_balInStrat > totalDebt) { totalUnderlying = _balInVault.add(totalDebt); } else { totalUnderlying = _balInVault.add(_balInStrat); } uint totalShares = totalSupply(); if (totalShares > 0) { return _shares.mul(totalUnderlying) / totalShares; } return 0; } /* @notice Calculate amount of underlying token that can be withdrawn @param _shares Amount of shares @return Amount of underlying token that can be withdrawn */ function getExpectedReturn(uint _shares) external view override returns (uint) { uint balInVault = _balanceInVault(); uint balInStrat = _balanceInStrategy(); return _getExpectedReturn(_shares, balInVault, balInStrat); } /* @notice Withdraw underlying token @param _shares Amount of shares to burn @param _min Minimum amount of underlying token to return @dev Keep `guard` modifier, else attacker can deposit and then use smart contract to attack from withdraw */ function withdraw(uint _shares, uint _min) external override nonReentrant guard { require(_shares > 0, "shares = 0"); uint balInVault = _balanceInVault(); uint balInStrat = _balanceInStrategy(); uint withdrawAmount = _getExpectedReturn(_shares, balInVault, balInStrat); // Must burn after calculating withdraw amount _burn(msg.sender, _shares); if (balInVault < withdrawAmount) { // maximize withdraw amount from strategy uint amountFromStrat = withdrawAmount; if (balInStrat < withdrawAmount) { amountFromStrat = balInStrat; } IStrategy(strategy).withdraw(amountFromStrat); uint balAfter = _balanceInVault(); uint diff = balAfter.sub(balInVault); if (diff < amountFromStrat) { // withdraw amount - withdraw amount from strat = amount to withdraw from vault // diff = actual amount returned from strategy // NOTE: withdrawAmount >= amountFromStrat withdrawAmount = (withdrawAmount - amountFromStrat).add(diff); } // transfer to treasury uint fee = withdrawAmount.mul(withdrawFee) / FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); withdrawAmount = withdrawAmount - fee; IERC20(token).safeTransfer(treasury, fee); } } require(withdrawAmount >= _min, "withdraw < min"); IERC20(token).safeTransfer(msg.sender, withdrawAmount); } /* @notice Transfer token != underlying token in vault to admin @param _token Address of token to transfer @dev Must transfer token to admin @dev _token must not be equal to underlying token @dev Used to transfer token that was accidentally sent to this vault */ function sweep(address _token) external override onlyAdmin { require(_token != token, "token = vault.token"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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]. */ 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; 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; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../protocol/IController.sol"; /* solium-disable */ contract MockController is IController { bytes32 public constant override ADMIN_ROLE = keccak256(abi.encodePacked("ADMIN")); bytes32 public constant override HARVESTER_ROLE = keccak256(abi.encodePacked("HARVESTER")); address public override admin; address public override treasury; constructor(address _treasury) public { admin = msg.sender; treasury = _treasury; } function setAdmin(address _admin) external override {} function setTreasury(address _treasury) external override {} function grantRole(bytes32 _role, address _addr) external override {} function revokeRole(bytes32 _role, address _addr) external override {} function invest(address _vault) external override {} function setStrategy( address _vault, address _strategy, uint _min ) external override {} function harvest(address _strategy) external override {} function skim(address _strategy) external override {} function withdraw( address _strategy, uint _amount, uint _min ) external override {} function withdrawAll(address _strategy, uint _min) external override {} function exit(address _strategy, uint _min) external override {} /* test helper */ function _setTreasury_(address _treasury) external { treasury = _treasury; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./protocol/IStrategy.sol"; import "./protocol/IController.sol"; abstract contract StrategyBase is IStrategy { using SafeERC20 for IERC20; using SafeMath for uint; address public override admin; address public override controller; address public override vault; address public override underlying; // total amount of underlying transferred from vault uint public override totalDebt; // performance fee sent to treasury when harvest() generates profit uint public override performanceFee = 100; uint internal constant PERFORMANCE_FEE_MAX = 10000; // valuable tokens that cannot be swept mapping(address => bool) public override assets; constructor( address _controller, address _vault, address _underlying ) public { require(_controller != address(0), "controller = zero address"); require(_vault != address(0), "vault = zero address"); require(_underlying != address(0), "underlying = zero address"); admin = msg.sender; controller = _controller; vault = _vault; underlying = _underlying; assets[underlying] = true; } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier onlyAuthorized() { require( msg.sender == admin || msg.sender == controller || msg.sender == vault, "!authorized" ); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } function setController(address _controller) external override onlyAdmin { require(_controller != address(0), "controller = zero address"); controller = _controller; } function setPerformanceFee(uint _fee) external override onlyAdmin { require(_fee <= PERFORMANCE_FEE_MAX, "performance fee > max"); performanceFee = _fee; } function _increaseDebt(uint _underlyingAmount) private { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransferFrom(vault, address(this), _underlyingAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); totalDebt = totalDebt.add(balAfter.sub(balBefore)); } function _decreaseDebt(uint _underlyingAmount) private { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransfer(vault, _underlyingAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balBefore.sub(balAfter); if (diff > totalDebt) { totalDebt = 0; } else { totalDebt = totalDebt - diff; } } function _totalAssets() internal view virtual returns (uint); /* @notice Returns amount of underlying tokens locked in this contract */ function totalAssets() external view override returns (uint) { return _totalAssets(); } function _depositUnderlying() internal virtual; /* @notice Deposit underlying token into this strategy @param _underlyingAmount Amount of underlying token to deposit */ function deposit(uint _underlyingAmount) external override onlyAuthorized { require(_underlyingAmount > 0, "underlying = 0"); _increaseDebt(_underlyingAmount); _depositUnderlying(); } /* @notice Returns total shares owned by this contract for depositing underlying into external Defi */ function _getTotalShares() internal view virtual returns (uint); function _getShares(uint _underlyingAmount, uint _totalUnderlying) internal view returns (uint) { /* calculate shares to withdraw w = amount of underlying to withdraw U = total redeemable underlying s = shares to withdraw P = total shares deposited into external liquidity pool w / U = s / P s = w / U * P */ if (_totalUnderlying > 0) { uint totalShares = _getTotalShares(); return _underlyingAmount.mul(totalShares) / _totalUnderlying; } return 0; } function _withdrawUnderlying(uint _shares) internal virtual; /* @notice Withdraw undelying token to vault @param _underlyingAmount Amount of underlying token to withdraw @dev Caller should implement guard agains slippage */ function withdraw(uint _underlyingAmount) external override onlyAuthorized { require(_underlyingAmount > 0, "underlying = 0"); uint totalUnderlying = _totalAssets(); require(_underlyingAmount <= totalUnderlying, "underlying > total"); uint shares = _getShares(_underlyingAmount, totalUnderlying); if (shares > 0) { _withdrawUnderlying(shares); } // transfer underlying token to vault uint underlyingBal = IERC20(underlying).balanceOf(address(this)); if (underlyingBal > 0) { _decreaseDebt(underlyingBal); } } function _withdrawAll() internal { uint totalShares = _getTotalShares(); if (totalShares > 0) { _withdrawUnderlying(totalShares); } uint underlyingBal = IERC20(underlying).balanceOf(address(this)); if (underlyingBal > 0) { _decreaseDebt(underlyingBal); totalDebt = 0; } } /* @notice Withdraw all underlying to vault @dev Caller should implement guard agains slippage */ function withdrawAll() external override onlyAuthorized { _withdrawAll(); } /* @notice Sell any staking rewards for underlying, deposit or transfer undelying depending on total debt */ function harvest() external virtual override; /* @notice Transfer profit over total debt to vault */ function skim() external override onlyAuthorized { uint totalUnderlying = _totalAssets(); if (totalUnderlying > totalDebt) { uint profit = totalUnderlying - totalDebt; uint shares = _getShares(profit, totalUnderlying); if (shares > 0) { uint balBefore = IERC20(underlying).balanceOf(address(this)); _withdrawUnderlying(shares); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balAfter.sub(balBefore); if (diff > 0) { IERC20(underlying).safeTransfer(vault, diff); } } } } function exit() external virtual override; function sweep(address _token) external override onlyAdmin { require(!assets[_token], "asset"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../StrategyBase.sol"; import "./TestToken.sol"; /* solium-disable */ contract StrategyTest is StrategyBase { // test helper uint public _depositAmount_; uint public _withdrawAmount_; bool public _harvestWasCalled_; bool public _exitWasCalled_; // simulate strategy withdrawing less than requested uint public _maxWithdrawAmount_ = uint(-1); // mock liquidity provider address public constant _POOL_ = address(1); constructor( address _controller, address _vault, address _underlying ) public StrategyBase(_controller, _vault, _underlying) { // allow this contract to freely withdraw from POOL TestToken(underlying)._approve_(_POOL_, address(this), uint(-1)); } function _totalAssets() internal view override returns (uint) { return IERC20(underlying).balanceOf(_POOL_); } function _depositUnderlying() internal override { uint bal = IERC20(underlying).balanceOf(address(this)); _depositAmount_ = bal; IERC20(underlying).transfer(_POOL_, bal); } function _getTotalShares() internal view override returns (uint) { return IERC20(underlying).balanceOf(_POOL_); } function _withdrawUnderlying(uint _shares) internal override { _withdrawAmount_ = _shares; if (_shares > _maxWithdrawAmount_) { _withdrawAmount_ = _maxWithdrawAmount_; } IERC20(underlying).transferFrom(_POOL_, address(this), _withdrawAmount_); } function harvest() external override onlyAuthorized { _harvestWasCalled_ = true; } function exit() external override onlyAuthorized { _exitWasCalled_ = true; _withdrawAll(); } // test helpers function _setVault_(address _vault) external { vault = _vault; } function _setUnderlying_(address _token) external { underlying = _token; } function _setAsset_(address _token) external { assets[_token] = true; } function _mintToPool_(uint _amount) external { TestToken(underlying)._mint_(_POOL_, _amount); } function _setTotalDebt_(uint _debt) external { totalDebt = _debt; } function _setMaxWithdrawAmount_(uint _max) external { _maxWithdrawAmount_ = _max; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /* solium-disable */ contract TestToken is ERC20 { constructor() public ERC20("test", "TEST") { _setupDecimals(18); } /* test helper */ function _mint_(address _to, uint _amount) external { _mint(_to, _amount); } function _burn_(address _from, uint _amount) external { _burn(_from, _amount); } function _approve_( address _from, address _to, uint _amount ) external { _approve(_from, _to, _amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../protocol/IStrategy.sol"; /* This is a "placeholder" strategy used during emergency shutdown */ contract StrategyNoOp is IStrategy { using SafeERC20 for IERC20; address public override admin; address public override controller; address public override vault; address public override underlying; uint public override totalDebt; uint public override performanceFee; mapping(address => bool) public override assets; constructor( address _controller, address _vault, address _underlying ) public { require(_controller != address(0), "controller = zero address"); require(_vault != address(0), "vault = zero address"); require(_underlying != address(0), "underlying = zero address"); admin = msg.sender; controller = _controller; vault = _vault; underlying = _underlying; assets[underlying] = true; } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } // @dev variable name is removed to silence compiler warning function setController(address) external override { revert("no-op"); } // @dev variable name is removed to silence compiler warning function setPerformanceFee(uint) external override { revert("no-op"); } function totalAssets() external view override returns (uint) { return 0; } // @dev variable name is removed to silence compiler warning function deposit(uint) external override { revert("no-op"); } // @dev variable name is removed to silence compiler warning function withdraw(uint) external override { revert("no-op"); } function withdrawAll() external override { revert("no-op"); } function harvest() external override { revert("no-op"); } function skim() external override { revert("no-op"); } function exit() external override { // left as blank so that Vault can call exit() during Vault.setStrategy() } function sweep(address _token) external override onlyAdmin { require(!assets[_token], "asset"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/uniswap/Uniswap.sol"; contract UseUniswap { using SafeERC20 for IERC20; using SafeMath for uint; // Uniswap // address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; function _swap( address _from, address _to, uint _amount ) internal { require(_to != address(0), "to = zero address"); // Swap with uniswap IERC20(_from).safeApprove(UNISWAP, 0); IERC20(_from).safeApprove(UNISWAP, _amount); address[] memory path; if (_from == WETH || _to == WETH) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; } Uniswap(UNISWAP).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface Uniswap { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/pickle/PickleJar.sol"; import "../interfaces/pickle/MasterChef.sol"; import "../interfaces/pickle/PickleStaking.sol"; import "../StrategyBase.sol"; import "../UseUniswap.sol"; contract StrategyPdaiDai is StrategyBase, UseUniswap { address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // Pickle // address private constant JAR = 0x6949Bb624E8e8A90F87cD2058139fcd77D2F3F87; address private constant CHEF = 0xbD17B1ce622d73bD438b9E658acA5996dc394b0d; address private constant PICKLE = 0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5; address private constant STAKING = 0xa17a8883dA1aBd57c690DF9Ebf58fC194eDAb66F; // percentage of Pickle to sell, rest is staked uint public pickleSell = 5000; uint private constant PICKLE_SELL_MAX = 10000; // POOL ID for PDAI JAR uint private constant POOL_ID = 16; constructor(address _controller, address _vault) public StrategyBase(_controller, _vault, DAI) { // Assets that cannot be swept by admin assets[PICKLE] = true; } function setPickleSell(uint _sell) external onlyAdmin { require(_sell <= PICKLE_SELL_MAX, "sell > max"); pickleSell = _sell; } // TODO security: vulnerable to price manipulation? function _totalAssets() internal view override returns (uint) { // getRatio() is multiplied by 10 ** 18 uint pricePerShare = PickleJar(JAR).getRatio(); (uint shares, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this)); return shares.mul(pricePerShare).div(1e18); } function _depositUnderlying() internal override { // deposit DAI into PICKLE uint bal = IERC20(underlying).balanceOf(address(this)); if (bal > 0) { IERC20(underlying).safeApprove(JAR, 0); IERC20(underlying).safeApprove(JAR, bal); PickleJar(JAR).deposit(bal); } // stake pDai uint pDaiBal = IERC20(JAR).balanceOf(address(this)); if (pDaiBal > 0) { IERC20(JAR).safeApprove(CHEF, 0); IERC20(JAR).safeApprove(CHEF, pDaiBal); MasterChef(CHEF).deposit(POOL_ID, pDaiBal); } // stake PICKLE uint pickleBal = IERC20(PICKLE).balanceOf(address(this)); if (pickleBal > 0) { IERC20(PICKLE).safeApprove(STAKING, 0); IERC20(PICKLE).safeApprove(STAKING, pickleBal); PickleStaking(STAKING).stake(pickleBal); } } function _getTotalShares() internal view override returns (uint) { (uint pDaiBal, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this)); return pDaiBal; } function _withdrawUnderlying(uint _pDaiAmount) internal override { // unstake MasterChef(CHEF).withdraw(POOL_ID, _pDaiAmount); // withdraw DAI from PICKLE PickleJar(JAR).withdraw(_pDaiAmount); // Now we have underlying } function _swapWeth() private { uint wethBal = IERC20(WETH).balanceOf(address(this)); if (wethBal > 0) { _swap(WETH, underlying, wethBal); // Now this contract has underlying token } } /* @notice Sell PICKLE and deposit most premium token into CURVE */ function harvest() external override onlyAuthorized { // claim Pickle MasterChef(CHEF).deposit(POOL_ID, 0); // unsold amount will be staked in _depositUnderlying() uint pickleBal = IERC20(PICKLE).balanceOf(address(this)); uint pickleAmount = pickleBal.mul(pickleSell).div(PICKLE_SELL_MAX); if (pickleAmount > 0) { _swap(PICKLE, underlying, pickleAmount); // Now this contract has underlying token } // get staking rewards WETH PickleStaking(STAKING).getReward(); _swapWeth(); uint bal = IERC20(underlying).balanceOf(address(this)); if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee).div(PERFORMANCE_FEE_MAX); if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); IERC20(underlying).safeTransfer(treasury, fee); } _depositUnderlying(); } } /* @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { /* PICKLE is minted on deposit / withdraw so here we 0. Unstake PICKLE and claim WETH rewards 1. Sell WETH 2. Withdraw from MasterChef 3. Sell PICKLE 4. Transfer underlying to vault */ uint staked = PickleStaking(STAKING).balanceOf(address(this)); if (staked > 0) { PickleStaking(STAKING).exit(); _swapWeth(); } _withdrawAll(); uint pickleBal = IERC20(PICKLE).balanceOf(address(this)); if (pickleBal > 0) { _swap(PICKLE, underlying, pickleBal); // Now this contract has underlying token } uint bal = IERC20(underlying).balanceOf(address(this)); if (bal > 0) { IERC20(underlying).safeTransfer(vault, bal); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface PickleJar { /* @notice returns price of token / share @dev ratio is multiplied by 10 ** 18 */ function getRatio() external view returns (uint); function deposit(uint _amount) external; function withdraw(uint _amount) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface MasterChef { function userInfo(uint _pid, address _user) external view returns (uint _amount, uint _rewardDebt); function deposit(uint _pid, uint _amount) external; function withdraw(uint _pid, uint _amount) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface PickleStaking { function balanceOf(address account) external view returns (uint); function earned(address account) external view returns (uint); function stake(uint amount) external; function withdraw(uint amount) external; function getReward() external; function exit() external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/StableSwap3.sol"; import "../interfaces/pickle/PickleJar.sol"; import "../interfaces/pickle/MasterChef.sol"; import "../StrategyBase.sol"; import "../UseUniswap.sol"; contract StrategyP3Crv is StrategyBase, UseUniswap { address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // DAI = 0 | USDC = 1 | USDT = 2 uint internal underlyingIndex; // precision to convert 10 ** 18 to underlying decimals uint internal precisionDiv = 1; // Curve // // 3Crv address private constant THREE_CRV = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; // StableSwap3 address private constant CURVE = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // Pickle // address private constant JAR = 0x1BB74b5DdC1f4fC91D6f9E7906cf68bc93538e33; address private constant CHEF = 0xbD17B1ce622d73bD438b9E658acA5996dc394b0d; address private constant PICKLE = 0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5; // POOL ID for 3Crv JAR uint private constant POOL_ID = 14; constructor( address _controller, address _vault, address _underlying ) public StrategyBase(_controller, _vault, _underlying) { // Assets that cannot be swept by admin assets[PICKLE] = true; } // TODO security: vulnerable to price manipulation function _totalAssets() internal view override returns (uint) { // getRatio() is multiplied by 10 ** 18 uint pricePerShare = PickleJar(JAR).getRatio(); (uint shares, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this)); return shares.mul(pricePerShare).div(precisionDiv) / 1e18; } function _deposit(address _token, uint _index) private { // token to THREE_CRV uint bal = IERC20(_token).balanceOf(address(this)); if (bal > 0) { IERC20(_token).safeApprove(CURVE, 0); IERC20(_token).safeApprove(CURVE, bal); // mint THREE_CRV uint[3] memory amounts; amounts[_index] = bal; StableSwap3(CURVE).add_liquidity(amounts, 0); // Now we have 3Crv } // deposit 3Crv into PICKLE uint threeBal = IERC20(THREE_CRV).balanceOf(address(this)); if (threeBal > 0) { IERC20(THREE_CRV).safeApprove(JAR, 0); IERC20(THREE_CRV).safeApprove(JAR, threeBal); PickleJar(JAR).deposit(threeBal); } // stake p3crv uint p3crvBal = IERC20(JAR).balanceOf(address(this)); if (p3crvBal > 0) { IERC20(JAR).safeApprove(CHEF, 0); IERC20(JAR).safeApprove(CHEF, p3crvBal); MasterChef(CHEF).deposit(POOL_ID, p3crvBal); } // TODO stake } function _depositUnderlying() internal override { _deposit(underlying, underlyingIndex); } function _getTotalShares() internal view override returns (uint) { (uint p3CrvBal, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this)); return p3CrvBal; } function _withdrawUnderlying(uint _p3CrvAmount) internal override { // unstake MasterChef(CHEF).withdraw(POOL_ID, _p3CrvAmount); // withdraw THREE_CRV from PICKLE PickleJar(JAR).withdraw(_p3CrvAmount); // withdraw underlying uint threeBal = IERC20(THREE_CRV).balanceOf(address(this)); // creates THREE_CRV dust StableSwap3(CURVE).remove_liquidity_one_coin( threeBal, int128(underlyingIndex), 0 ); // Now we have underlying } /* @notice Returns address and index of token with lowest balance in CURVE pool */ function _getMostPremiumToken() private view returns (address, uint) { uint[] memory balances = new uint[](3); balances[0] = StableSwap3(CURVE).balances(0); // DAI balances[1] = StableSwap3(CURVE).balances(1).mul(1e12); // USDC balances[2] = StableSwap3(CURVE).balances(2).mul(1e12); // USDT // DAI if (balances[0] <= balances[1] && balances[0] <= balances[2]) { return (DAI, 0); } // USDC if (balances[1] <= balances[0] && balances[1] <= balances[2]) { return (USDC, 1); } // USDT return (USDT, 2); } function _swapPickleFor(address _token) private { uint pickleBal = IERC20(PICKLE).balanceOf(address(this)); if (pickleBal > 0) { _swap(PICKLE, _token, pickleBal); // Now this contract has underlying token } } /* @notice Sell PICKLE and deposit most premium token into CURVE */ function harvest() external override onlyAuthorized { // TODO: claim Pickle // MasterChef(CHER).deposit(POOL_ID, 0); (address token, uint index) = _getMostPremiumToken(); _swapPickleFor(token); uint bal = IERC20(token).balanceOf(address(this)); if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); IERC20(token).safeTransfer(treasury, fee); } _deposit(token, index); } } /* @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { // PICKLE is minted on withdraw so here we // 1. Withdraw from MasterChef // 2. Sell PICKLE // 3. Transfer underlying to vault _withdrawAll(); _swapPickleFor(underlying); uint underlyingBal = IERC20(underlying).balanceOf(address(this)); if (underlyingBal > 0) { IERC20(underlying).safeTransfer(vault, underlyingBal); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface StableSwap3 { /* @dev Returns price of 1 Curve LP token in USD */ function get_virtual_price() external view returns (uint); function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin( uint token_amount, int128 i, uint min_uamount ) external; function balances(uint index) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyP3Crv.sol"; contract StrategyP3CrvUsdt is StrategyP3Crv { constructor(address _controller, address _vault) public StrategyP3Crv(_controller, _vault, USDT) { // usdt underlyingIndex = 2; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyP3Crv.sol"; contract StrategyP3CrvUsdc is StrategyP3Crv { constructor(address _controller, address _vault) public StrategyP3Crv(_controller, _vault, USDC) { // usdc underlyingIndex = 1; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyP3Crv.sol"; contract StrategyP3CrvDai is StrategyP3Crv { constructor(address _controller, address _vault) public StrategyP3Crv(_controller, _vault, DAI) { // dai underlyingIndex = 0; precisionDiv = 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/StableSwapGusd.sol"; import "../interfaces/curve/DepositGusd.sol"; import "../interfaces/curve/StableSwap3.sol"; import "./StrategyCurve.sol"; contract StrategyGusd is StrategyCurve { // 3Pool StableSwap address private constant BASE_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // GUSD StableSwap address private constant SWAP = 0x4f062658EaAF2C1ccf8C8e36D6824CDf41167956; address private constant GUSD = 0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd; address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; constructor( address _controller, address _vault, address _underlying ) public StrategyCurve(_controller, _vault, _underlying) { // Curve // GUSD / 3CRV lp = 0xD2967f45c4f384DEEa880F807Be904762a3DeA07; // DepositGusd pool = 0x64448B78561690B70E17CBE8029a3e5c1bB7136e; // Gauge gauge = 0xC5cfaDA84E902aD92DD40194f0883ad49639b023; // Minter minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // DAO crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; } function _getVirtualPrice() internal view override returns (uint) { return StableSwapGusd(SWAP).get_virtual_price(); } function _addLiquidity(uint _amount, uint _index) internal override { uint[4] memory amounts; amounts[_index] = _amount; DepositGusd(pool).add_liquidity(amounts, 0); } function _removeLiquidityOneCoin(uint _lpAmount) internal override { IERC20(lp).safeApprove(pool, 0); IERC20(lp).safeApprove(pool, _lpAmount); DepositGusd(pool).remove_liquidity_one_coin( _lpAmount, int128(underlyingIndex), 0 ); } function _getMostPremiumToken() internal view override returns (address, uint) { uint[4] memory balances; balances[0] = StableSwapGusd(SWAP).balances(0).mul(1e16); // GUSD balances[1] = StableSwap3(BASE_POOL).balances(0); // DAI balances[2] = StableSwap3(BASE_POOL).balances(1).mul(1e12); // USDC balances[3] = StableSwap3(BASE_POOL).balances(2).mul(1e12); // USDT uint minIndex = 0; for (uint i = 1; i < balances.length; i++) { if (balances[i] <= balances[minIndex]) { minIndex = i; } } if (minIndex == 0) { return (GUSD, 0); } if (minIndex == 1) { return (DAI, 1); } if (minIndex == 2) { return (USDC, 2); } return (USDT, 3); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface StableSwapGusd { function get_virtual_price() external view returns (uint); /* 0 GUSD 1 3CRV */ function balances(uint index) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface DepositGusd { /* 0 GUSD 1 DAI 2 USDC 3 USDT */ function add_liquidity(uint[4] memory amounts, uint min) external returns (uint); function remove_liquidity_one_coin( uint amount, int128 index, uint min ) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/Gauge.sol"; import "../interfaces/curve/Minter.sol"; import "../StrategyBase.sol"; import "../UseUniswap.sol"; /* potential hacks? - front running? - slippage when withdrawing all from strategy */ abstract contract StrategyCurve is StrategyBase, UseUniswap { // DAI = 0 | USDC = 1 | USDT = 2 uint internal underlyingIndex; // precision to convert 10 ** 18 to underlying decimals uint internal precisionDiv = 1; // Curve // // liquidity provider token (cDAI/cUSDC or 3Crv) address internal lp; // ICurveFi2 or ICurveFi3 address internal pool; // Gauge address internal gauge; // Minter address internal minter; // DAO address internal crv; constructor( address _controller, address _vault, address _underlying ) public StrategyBase(_controller, _vault, _underlying) {} function _getVirtualPrice() internal view virtual returns (uint); function _totalAssets() internal view override returns (uint) { uint lpBal = Gauge(gauge).balanceOf(address(this)); uint pricePerShare = _getVirtualPrice(); return lpBal.mul(pricePerShare).div(precisionDiv) / 1e18; } function _addLiquidity(uint _amount, uint _index) internal virtual; /* @notice deposit token into curve */ function _deposit(address _token, uint _index) private { // token to lp uint bal = IERC20(_token).balanceOf(address(this)); if (bal > 0) { IERC20(_token).safeApprove(pool, 0); IERC20(_token).safeApprove(pool, bal); // mint lp _addLiquidity(bal, _index); } // stake into Gauge uint lpBal = IERC20(lp).balanceOf(address(this)); if (lpBal > 0) { IERC20(lp).safeApprove(gauge, 0); IERC20(lp).safeApprove(gauge, lpBal); Gauge(gauge).deposit(lpBal); } } /* @notice Deposits underlying to Gauge */ function _depositUnderlying() internal override { _deposit(underlying, underlyingIndex); } function _removeLiquidityOneCoin(uint _lpAmount) internal virtual; function _getTotalShares() internal view override returns (uint) { return Gauge(gauge).balanceOf(address(this)); } function _withdrawUnderlying(uint _lpAmount) internal override { // withdraw lp from Gauge Gauge(gauge).withdraw(_lpAmount); // withdraw underlying uint lpBal = IERC20(lp).balanceOf(address(this)); // creates lp dust _removeLiquidityOneCoin(lpBal); // Now we have underlying } /* @notice Returns address and index of token with lowest balance in Curve pool */ function _getMostPremiumToken() internal view virtual returns (address, uint); function _swapCrvFor(address _token) private { Minter(minter).mint(gauge); uint crvBal = IERC20(crv).balanceOf(address(this)); if (crvBal > 0) { _swap(crv, _token, crvBal); // Now this contract has token } } /* @notice Claim CRV and deposit most premium token into Curve */ function harvest() external override onlyAuthorized { (address token, uint index) = _getMostPremiumToken(); _swapCrvFor(token); uint bal = IERC20(token).balanceOf(address(this)); if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); IERC20(token).safeTransfer(treasury, fee); } _deposit(token, index); } } /* @notice Exit strategy by harvesting CRV to underlying token and then withdrawing all underlying to vault @dev Must return all underlying token to vault @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { _swapCrvFor(underlying); _withdrawAll(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; // https://github.com/curvefi/curve-contract/blob/master/contracts/gauges/LiquidityGauge.vy interface Gauge { function deposit(uint) external; function balanceOf(address) external view returns (uint); function withdraw(uint) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; // https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/Minter.vy interface Minter { function mint(address) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyGusd.sol"; contract StrategyGusdUsdt is StrategyGusd { constructor(address _controller, address _vault) public StrategyGusd(_controller, _vault, USDT) { // usdt underlyingIndex = 3; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyGusd.sol"; contract StrategyGusdUsdc is StrategyGusd { constructor(address _controller, address _vault) public StrategyGusd(_controller, _vault, USDC) { // usdc underlyingIndex = 2; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyGusd.sol"; contract StrategyGusdDai is StrategyGusd { constructor(address _controller, address _vault) public StrategyGusd(_controller, _vault, DAI) { // dai underlyingIndex = 1; precisionDiv = 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/StableSwapPax.sol"; import "../interfaces/curve/DepositPax.sol"; import "./StrategyCurve.sol"; contract StrategyPax is StrategyCurve { // PAX StableSwap address private constant SWAP = 0x06364f10B501e868329afBc005b3492902d6C763; address private constant PAX = 0x8E870D67F660D95d5be530380D0eC0bd388289E1; address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; constructor( address _controller, address _vault, address _underlying ) public StrategyCurve(_controller, _vault, _underlying) { // Curve // DAI/USDC/USDT/PAX lp = 0xD905e2eaeBe188fc92179b6350807D8bd91Db0D8; // DepositPax pool = 0xA50cCc70b6a011CffDdf45057E39679379187287; // Gauge gauge = 0x64E3C23bfc40722d3B649844055F1D51c1ac041d; // Minter minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // DAO crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; } function _getVirtualPrice() internal view override returns (uint) { return StableSwapPax(SWAP).get_virtual_price(); } function _addLiquidity(uint _amount, uint _index) internal override { uint[4] memory amounts; amounts[_index] = _amount; DepositPax(pool).add_liquidity(amounts, 0); } function _removeLiquidityOneCoin(uint _lpAmount) internal override { IERC20(lp).safeApprove(pool, 0); IERC20(lp).safeApprove(pool, _lpAmount); DepositPax(pool).remove_liquidity_one_coin( _lpAmount, int128(underlyingIndex), 0, false ); } function _getMostPremiumToken() internal view override returns (address, uint) { uint[4] memory balances; balances[0] = StableSwapPax(SWAP).balances(0); // DAI balances[1] = StableSwapPax(SWAP).balances(1).mul(1e12); // USDC balances[2] = StableSwapPax(SWAP).balances(2).mul(1e12); // USDT balances[3] = StableSwapPax(SWAP).balances(3); // PAX uint minIndex = 0; for (uint i = 1; i < balances.length; i++) { if (balances[i] <= balances[minIndex]) { minIndex = i; } } if (minIndex == 0) { return (DAI, 0); } if (minIndex == 1) { return (USDC, 1); } if (minIndex == 2) { return (USDT, 2); } return (PAX, 3); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface StableSwapPax { function get_virtual_price() external view returns (uint); /* 0 DAI 1 USDC 2 USDT 3 PAX */ function balances(int128 index) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface DepositPax { /* 0 DAI 1 USDC 2 USDT 3 PAX */ function add_liquidity(uint[4] memory amounts, uint min) external; function remove_liquidity_one_coin( uint amount, int128 index, uint min, bool donateDust ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyPax.sol"; contract StrategyPaxUsdt is StrategyPax { constructor(address _controller, address _vault) public StrategyPax(_controller, _vault, USDT) { // usdt underlyingIndex = 2; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyPax.sol"; contract StrategyPaxUsdc is StrategyPax { constructor(address _controller, address _vault) public StrategyPax(_controller, _vault, USDC) { // usdc underlyingIndex = 1; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyPax.sol"; contract StrategyPaxDai is StrategyPax { constructor(address _controller, address _vault) public StrategyPax(_controller, _vault, DAI) { // dai underlyingIndex = 0; precisionDiv = 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/StableSwap2.sol"; import "../interfaces/curve/Deposit2.sol"; import "./StrategyCurve.sol"; contract StrategyCusd is StrategyCurve { address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address private constant SWAP = 0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56; constructor( address _controller, address _vault, address _underlying ) public StrategyCurve(_controller, _vault, _underlying) { // Curve // cDAI/cUSDC lp = 0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2; // DepositCompound pool = 0xeB21209ae4C2c9FF2a86ACA31E123764A3B6Bc06; // Gauge gauge = 0x7ca5b0a2910B33e9759DC7dDB0413949071D7575; // Minter minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // DAO crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; } /* @dev Returns USD price of 1 Curve Compound LP token */ function _getVirtualPrice() internal view override returns (uint) { return StableSwap2(SWAP).get_virtual_price(); } function _addLiquidity(uint _amount, uint _index) internal override { uint[2] memory amounts; amounts[_index] = _amount; Deposit2(pool).add_liquidity(amounts, 0); } function _removeLiquidityOneCoin(uint _lpAmount) internal override { IERC20(lp).safeApprove(pool, 0); IERC20(lp).safeApprove(pool, _lpAmount); Deposit2(pool).remove_liquidity_one_coin( _lpAmount, int128(underlyingIndex), 0, true ); } function _getMostPremiumToken() internal view override returns (address, uint) { uint[] memory balances = new uint[](2); balances[0] = StableSwap2(SWAP).balances(0); // DAI balances[1] = StableSwap2(SWAP).balances(1).mul(1e12); // USDC // DAI if (balances[0] < balances[1]) { return (DAI, 0); } return (USDC, 1); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface StableSwap2 { /* @dev Returns price of 1 Curve LP token in USD */ function get_virtual_price() external view returns (uint); function add_liquidity(uint[2] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin( uint token_amount, int128 i, uint min_uamount, bool donate_dust ) external; function balances(int128 index) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface Deposit2 { function add_liquidity(uint[2] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin( uint token_amount, int128 i, uint min_uamount, bool donate_dust ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyCusd.sol"; contract StrategyCusdUsdc is StrategyCusd { constructor(address _controller, address _vault) public StrategyCusd(_controller, _vault, USDC) { // usdc underlyingIndex = 1; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyCusd.sol"; contract StrategyCusdDai is StrategyCusd { constructor(address _controller, address _vault) public StrategyCusd(_controller, _vault, DAI) { // dai underlyingIndex = 0; precisionDiv = 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/StableSwapBusd.sol"; import "../interfaces/curve/DepositBusd.sol"; import "./StrategyCurve.sol"; contract StrategyBusd is StrategyCurve { // BUSD StableSwap address private constant SWAP = 0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27; address private constant BUSD = 0x4Fabb145d64652a948d72533023f6E7A623C7C53; address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; constructor( address _controller, address _vault, address _underlying ) public StrategyCurve(_controller, _vault, _underlying) { // Curve // yDAI/yUSDC/yUSDT/yBUSD lp = 0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B; // DepositBusd pool = 0xb6c057591E073249F2D9D88Ba59a46CFC9B59EdB; // Gauge gauge = 0x69Fb7c45726cfE2baDeE8317005d3F94bE838840; // Minter minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // DAO crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; } function _getVirtualPrice() internal view override returns (uint) { return StableSwapBusd(SWAP).get_virtual_price(); } function _addLiquidity(uint _amount, uint _index) internal override { uint[4] memory amounts; amounts[_index] = _amount; DepositBusd(pool).add_liquidity(amounts, 0); } function _removeLiquidityOneCoin(uint _lpAmount) internal override { IERC20(lp).safeApprove(pool, 0); IERC20(lp).safeApprove(pool, _lpAmount); DepositBusd(pool).remove_liquidity_one_coin( _lpAmount, int128(underlyingIndex), 0, false ); } function _getMostPremiumToken() internal view override returns (address, uint) { uint[4] memory balances; balances[0] = StableSwapBusd(SWAP).balances(0); // DAI balances[1] = StableSwapBusd(SWAP).balances(1).mul(1e12); // USDC balances[2] = StableSwapBusd(SWAP).balances(2).mul(1e12); // USDT balances[3] = StableSwapBusd(SWAP).balances(3); // BUSD uint minIndex = 0; for (uint i = 1; i < balances.length; i++) { if (balances[i] <= balances[minIndex]) { minIndex = i; } } if (minIndex == 0) { return (DAI, 0); } if (minIndex == 1) { return (USDC, 1); } if (minIndex == 2) { return (USDT, 2); } return (BUSD, 3); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface StableSwapBusd { function get_virtual_price() external view returns (uint); /* 0 DAI 1 USDC 2 USDT 3 BUSD */ function balances(int128 index) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface DepositBusd { /* 0 DAI 1 USDC 2 USDT 3 BUSD */ function add_liquidity(uint[4] memory amounts, uint min) external; function remove_liquidity_one_coin( uint amount, int128 index, uint min, bool donateDust ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyBusd.sol"; contract StrategyBusdUsdt is StrategyBusd { constructor(address _controller, address _vault) public StrategyBusd(_controller, _vault, USDT) { // usdt underlyingIndex = 2; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyBusd.sol"; contract StrategyBusdUsdc is StrategyBusd { constructor(address _controller, address _vault) public StrategyBusd(_controller, _vault, USDC) { // usdc underlyingIndex = 1; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyBusd.sol"; contract StrategyBusdDai is StrategyBusd { constructor(address _controller, address _vault) public StrategyBusd(_controller, _vault, DAI) { // dai underlyingIndex = 0; precisionDiv = 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/StableSwap3.sol"; import "./StrategyCurve.sol"; contract Strategy3Crv is StrategyCurve { address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; constructor( address _controller, address _vault, address _underlying ) public StrategyCurve(_controller, _vault, _underlying) { // Curve // 3Crv lp = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; // 3 Pool pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // Gauge gauge = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A; // Minter minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // DAO crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; } function _getVirtualPrice() internal view override returns (uint) { return StableSwap3(pool).get_virtual_price(); } function _addLiquidity(uint _amount, uint _index) internal override { uint[3] memory amounts; amounts[_index] = _amount; StableSwap3(pool).add_liquidity(amounts, 0); } function _removeLiquidityOneCoin(uint _lpAmount) internal override { StableSwap3(pool).remove_liquidity_one_coin( _lpAmount, int128(underlyingIndex), 0 ); } function _getMostPremiumToken() internal view override returns (address, uint) { uint[] memory balances = new uint[](3); balances[0] = StableSwap3(pool).balances(0); // DAI balances[1] = StableSwap3(pool).balances(1).mul(1e12); // USDC balances[2] = StableSwap3(pool).balances(2).mul(1e12); // USDT // DAI if (balances[0] <= balances[1] && balances[0] <= balances[2]) { return (DAI, 0); } // USDC if (balances[1] <= balances[0] && balances[1] <= balances[2]) { return (USDC, 1); } return (USDT, 2); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./Strategy3Crv.sol"; contract Strategy3CrvUsdt is Strategy3Crv { constructor(address _controller, address _vault) public Strategy3Crv(_controller, _vault, USDT) { // usdt underlyingIndex = 2; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./Strategy3Crv.sol"; contract Strategy3CrvUsdc is Strategy3Crv { constructor(address _controller, address _vault) public Strategy3Crv(_controller, _vault, USDC) { // usdc underlyingIndex = 1; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./Strategy3Crv.sol"; contract Strategy3CrvDai is Strategy3Crv { constructor(address _controller, address _vault) public Strategy3Crv(_controller, _vault, DAI) { // dai underlyingIndex = 0; precisionDiv = 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./protocol/ITimeLock.sol"; contract TimeLock is ITimeLock { using SafeMath for uint; event NewAdmin(address admin); event NewDelay(uint delay); event Queue( bytes32 indexed txHash, address indexed target, uint value, bytes data, uint eta ); event Execute( bytes32 indexed txHash, address indexed target, uint value, bytes data, uint eta ); event Cancel( bytes32 indexed txHash, address indexed target, uint value, bytes data, uint eta ); uint public constant GRACE_PERIOD = 14 days; uint public constant MIN_DELAY = 1 days; uint public constant MAX_DELAY = 30 days; address public override admin; uint public override delay; mapping(bytes32 => bool) public override queued; constructor(uint _delay) public { admin = msg.sender; _setDelay(_delay); } receive() external payable override {} modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; emit NewAdmin(_admin); } function _setDelay(uint _delay) private { require(_delay >= MIN_DELAY, "delay < min"); require(_delay <= MAX_DELAY, "delay > max"); delay = _delay; emit NewDelay(delay); } /* @dev Only this contract can execute this function */ function setDelay(uint _delay) external override { require(msg.sender == address(this), "!timelock"); _setDelay(_delay); } function _getTxHash( address target, uint value, bytes memory data, uint eta ) private pure returns (bytes32) { return keccak256(abi.encode(target, value, data, eta)); } function getTxHash( address target, uint value, bytes calldata data, uint eta ) external pure override returns (bytes32) { return _getTxHash(target, value, data, eta); } /* @notice Queue transaction @param target Address of contract or account to call @param value Ether value to send @param data Data to send to `target` @eta Execute Tx After. Time after which transaction can be executed. */ function queue( address target, uint value, bytes calldata data, uint eta ) external override onlyAdmin returns (bytes32) { require(eta >= block.timestamp.add(delay), "eta < now + delay"); bytes32 txHash = _getTxHash(target, value, data, eta); queued[txHash] = true; emit Queue(txHash, target, value, data, eta); return txHash; } function execute( address target, uint value, bytes calldata data, uint eta ) external payable override onlyAdmin returns (bytes memory) { bytes32 txHash = _getTxHash(target, value, data, eta); require(queued[txHash], "!queued"); require(block.timestamp >= eta, "eta < now"); require(block.timestamp <= eta.add(GRACE_PERIOD), "eta expired"); queued[txHash] = false; // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value: value}(data); require(success, "tx failed"); emit Execute(txHash, target, value, data, eta); return returnData; } function cancel( address target, uint value, bytes calldata data, uint eta ) external override onlyAdmin { bytes32 txHash = _getTxHash(target, value, data, eta); require(queued[txHash], "!queued"); queued[txHash] = false; emit Cancel(txHash, target, value, data, eta); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface ITimeLock { event NewAdmin(address admin); event NewDelay(uint delay); event Queue( bytes32 indexed txHash, address indexed target, uint value, bytes data, uint eta ); event Execute( bytes32 indexed txHash, address indexed target, uint value, bytes data, uint eta ); event Cancel( bytes32 indexed txHash, address indexed target, uint value, bytes data, uint eta ); function admin() external view returns (address); function delay() external view returns (uint); function queued(bytes32 _txHash) external view returns (bool); function setAdmin(address _admin) external; function setDelay(uint _delay) external; receive() external payable; function getTxHash( address target, uint value, bytes calldata data, uint eta ) external pure returns (bytes32); function queue( address target, uint value, bytes calldata data, uint eta ) external returns (bytes32); function execute( address target, uint value, bytes calldata data, uint eta ) external payable returns (bytes memory); function cancel( address target, uint value, bytes calldata data, uint eta ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../protocol/IVault.sol"; /* solium-disable */ contract MockVault is IVault { address public override admin; address public override controller; address public override token; address public override strategy; address public override timeLock; uint public override reserveMin; uint public override withdrawFee; bool public override paused; mapping(address => bool) public override strategies; mapping(address => bool) public override whitelist; // test helpers uint public _setStrategyMin_; bool public _investWasCalled_; uint public _depositAmount_; uint public _withdrawAmount_; uint public _withdrawMin_; constructor( address _controller, address _timeLock, address _token ) public { admin = msg.sender; controller = _controller; timeLock = _timeLock; token = _token; } function setAdmin(address _admin) external override {} function setController(address _controller) external override {} function setTimeLock(address _timeLock) external override {} function setPause(bool _paused) external override {} function setWhitelist(address _addr, bool _approve) external override {} function setReserveMin(uint _min) external override {} function setWithdrawFee(uint _fee) external override {} function approveStrategy(address _strategy) external override {} function revokeStrategy(address _strategy) external override {} function setStrategy(address _strategy, uint _min) external override { strategy = _strategy; _setStrategyMin_ = _min; } function balanceInVault() external view override returns (uint) { return 0; } function balanceInStrategy() external view override returns (uint) { return 0; } function totalDebtInStrategy() external view override returns (uint) { return 0; } function totalAssets() external view override returns (uint) { return 0; } function minReserve() external view override returns (uint) { return 0; } function availableToInvest() external view override returns (uint) { return 0; } function invest() external override { _investWasCalled_ = true; } function deposit(uint _amount) external override { _depositAmount_ = _amount; } function getExpectedReturn(uint) external view override returns (uint) { return 0; } function withdraw(uint _shares, uint _min) external override { _withdrawAmount_ = _shares; _withdrawMin_ = _min; } function sweep(address _token) external override {} } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../protocol/IVault.sol"; /* solium-disable */ contract MockTimeLock { // test helpers function _setTimeLock_(address _vault, address _timeLock) external { IVault(_vault).setTimeLock(_timeLock); } function _approveStrategy_(address _vault, address _strategy) external { IVault(_vault).approveStrategy(_strategy); } }
https:github.com/curvefi/curve-dao-contracts/blob/master/contracts/Minter.vy
interface Minter { function mint(address) external; pragma solidity 0.6.11; }
13,453,132
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2020, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "arb-bridge-eth/contracts/libraries/Cloneable.sol"; import "../libraries/L2GatewayToken.sol"; import "../libraries/BytesParser.sol"; import "./IArbToken.sol"; /** * @title Standard (i.e., non-custom) contract deployed by L2Gateway.sol as L2 ERC20. Includes standard ERC20 interface plus additional methods for deposits/withdraws */ contract StandardArbERC20 is IArbToken, L2GatewayToken, Cloneable { struct ERC20Getters { bool ignoreDecimals; bool ignoreName; bool ignoreSymbol; } ERC20Getters private availableGetters; /** * @notice initialize the token * @dev the L2 bridge assumes this does not fail or revert * @param _l1Address L1 address of ERC20 * @param _data encoded symbol/name/decimal data for initial deploy */ function bridgeInit(address _l1Address, bytes memory _data) public virtual { (bytes memory name_, bytes memory symbol_, bytes memory decimals_) = abi.decode( _data, (bytes, bytes, bytes) ); // what if decode reverts? shouldn't as this is encoded by L1 contract /* * if parsing fails, the type's default value gets assigned * the parsing can fail for different reasons: * 1. method not available in L1 (empty input) * 2. data type is encoded differently in the L1 (trying to abi decode the wrong data type) * currently (1) returns a parser fails and (2) reverts as there is no `abi.tryDecode` * https://github.com/ethereum/solidity/issues/10381 */ (bool parseNameSuccess, string memory parsedName) = BytesParser.toString(name_); (bool parseSymbolSuccess, string memory parsedSymbol) = BytesParser.toString(symbol_); (bool parseDecimalSuccess, uint8 parsedDecimals) = BytesParser.toUint8(decimals_); L2GatewayToken._initialize( parsedName, parsedSymbol, parsedDecimals, msg.sender, // _l2Gateway, _l1Address // _l1Counterpart ); // here we assume that (2) would have reverted, so if the parser failed its because the getter isn't available in the L1. // instead of storing on a struct, we could instead set a magic number, at something like `type(uint8).max` or random string // to be more general we instead use an extra storage slot availableGetters = ERC20Getters({ ignoreName: !parseNameSuccess, ignoreSymbol: !parseSymbolSuccess, ignoreDecimals: !parseDecimalSuccess }); } function decimals() public view override returns (uint8) { // no revert message just as in the L1 if you called and the function is not implemented if (availableGetters.ignoreDecimals) revert(); return super.decimals(); } function name() public view override returns (string memory) { // no revert message just as in the L1 if you called and the function is not implemented if (availableGetters.ignoreName) revert(); return super.name(); } function symbol() public view override returns (string memory) { // no revert message just as in the L1 if you called and the function is not implemented if (availableGetters.ignoreSymbol) revert(); return super.symbol(); } }
no revert message just as in the L1 if you called and the function is not implemented
function name() public view override returns (string memory) { if (availableGetters.ignoreName) revert(); return super.name(); }
2,476,888
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; contract testStruct{ struct pessoas{ string nome; uint idade; } pessoas[] listaDePss; //Adicionando nome e idade (struct pessoas) na lista de pessoas. function adcPessoas(string memory _nome, uint _idade) external{ listaDePss.push(pessoas(_nome, _idade)); } //Retornando a lista de pessoas. function obterPessoas() public view returns (pessoas[] memory){ return listaDePss; } function obterPessoa(uint _indice) public view returns (string memory _nome, uint _idade){ pessoas memory p = listaDePss[_indice]; return (p.nome, p.idade); } function atualizarPessoas(uint _indice, string memory _nome, uint _idade) external{ pessoas storage p = listaDePss[_indice]; p.nome = _nome; p.idade = _idade; listaDePss[_indice] = p; } function deletarPessoas(uint _indice) external{ delete listaDePss[_indice]; } function totalPessoas() external view returns (uint){ return listaDePss.length; } /*Criar um laço de repetição (for) que quando o usuario insira o nome da pessoa retorne os dados dela*/ function acharPessoa(string memory _nome) external view returns (string memory _nomeV, uint _idade) { uint _indice = 0; for (uint i = 0; i < listaDePss.length; i++ ){ pessoas memory p = listaDePss[_indice]; string memory nomeV = p.nome; if (keccak256(abi.encodePacked(_nome)) != keccak256(abi.encodePacked(nomeV))){ _indice ++; continue; } else{ return (p.nome, p.idade); break; } } } }
Retornando a lista de pessoas.
function obterPessoas() public view returns (pessoas[] memory){ return listaDePss; }
12,915,124
./full_match/421613/0xC12b0fE62441bAAd525cd7d770cf21C883C77bc6/sources/contracts/controller/Controller.sol
Updates the treasury of an existing coordinator Must be called by the coordinator's current owner. Defaults to the coordinator `owner` if set to address(0) coordinatorId Coordinator to update newTreasury New treasury address/
function updateCoordinatorTreasury(uint256 coordinatorId, address newTreasury) external onlyOwner(coordinatorId) { _coordinators[coordinatorId].treasury = newTreasury; emit CoordinatorTreasuryUpdated(coordinatorId, newTreasury); }
11,574,475
pragma solidity ^0.4.24; import "../math/SafeMath.sol"; /** * @title SplitPayment * @dev This contract can be used when payments need to be received by a group * of people and split proportionately to some number of shares they own. */ contract SplitPayment { using SafeMath for uint256; uint256 private totalShares_ = 0; uint256 private totalReleased_ = 0; mapping(address => uint256) private shares_; mapping(address => uint256) private released_; address[] private payees_; /** * @dev Constructor */ constructor(address[] _payees, uint256[] _shares) public payable { require(_payees.length == _shares.length); require(_payees.length > 0); for (uint256 i = 0; i < _payees.length; i++) { _addPayee(_payees[i], _shares[i]); } } /** * @dev payable fallback */ function () external payable {} /** * @return the total shares of the contract. */ function totalShares() public view returns(uint256) { return totalShares_; } /** * @return the total amount already released. */ function totalReleased() public view returns(uint256) { return totalReleased_; } /** * @return the shares of an account. */ function shares(address _account) public view returns(uint256) { return shares_[_account]; } /** * @return the amount already released to an account. */ function released(address _account) public view returns(uint256) { return released_[_account]; } /** * @return the address of a payee. */ function payee(uint256 index) public view returns(address) { return payees_[index]; } /** * @dev Release one of the payee's proportional payment. * @param _payee Whose payments will be released. */ function release(address _payee) public { require(shares_[_payee] > 0); uint256 totalReceived = address(this).balance.add(totalReleased_); uint256 payment = totalReceived.mul( shares_[_payee]).div( totalShares_).sub( released_[_payee] ); require(payment != 0); assert(address(this).balance >= payment); released_[_payee] = released_[_payee].add(payment); totalReleased_ = totalReleased_.add(payment); _payee.transfer(payment); } /** * @dev Add a new payee to the contract. * @param _payee The address of the payee to add. * @param _shares The number of shares owned by the payee. */ function _addPayee(address _payee, uint256 _shares) internal { require(_payee != address(0)); require(_shares > 0); require(shares_[_payee] == 0); payees_.push(_payee); shares_[_payee] = _shares; totalShares_ = totalShares_.add(_shares); } }
return the shares of an account./
function shares(address _account) public view returns(uint256) { return shares_[_account]; }
13,046,274
./full_match/80001/0x060B3922eeCe531922d50FCdcbc0478fAA62A7fb/sources/contracts/extensions/ERC721Enumerable.sol
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. from address representing the previous owner of the given token ID tokenId uint256 ID of the token to be removed from the tokens list of the given address/ 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). When the token to delete is the last token, the swap operation is unnecessary
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721A.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; }
850,745
./partial_match/1/0xF36399Bf8CB0f47e6e79B1F615385e3A94C8473a/sources/contracts/modules/credit/LineOfCredit.sol
see ILineOfCredit.setRates
function setRates(bytes32 id, uint128 drate, uint128 frate) external override mutualConsentById(id) { credits[id] = _accrue(credits[id], id); _setRates(id, drate, frate); }
4,128,885
pragma solidity ^0.4.12; contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract StandardToken is ERC20, SafeMath { mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; function transfer(address _to, uint _value) returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) returns (bool success) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because safeSub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract UBetCoin is Ownable, StandardToken { string public name = "UBetCoin"; // name of the token string public symbol = "UBET"; // ERC20 compliant 4 digit token code uint public decimals = 2; // token has 2 digit precision uint256 public totalSupply = 400000000000; // 4 BILLION INITIAL SUPPLY uint256 public tokenSupplyFromCheck = 0; // Total from check! uint256 public tokenSupplyBackedByGold = 4000000000; // Supply Backed By Gold string public constant YOU_BET_MINE_DOCUMENT_PATH = "https://s3.amazonaws.com/s3-ubetcoin-user-signatures/document/GOLD-MINES-assigned+TO-SAINT-NICOLAS-SNADCO-03-22-2016.pdf"; string public constant YOU_BET_MINE_DOCUMENT_SHA512 = "7e9dc6362c5bf85ff19d75df9140b033c4121ba8aaef7e5837b276d657becf0a0d68fcf26b95e76023a33251ac94f35492f2f0af882af4b87b1b1b626b325cf8"; string public constant UBETCOIN_LEDGER_TO_LEDGER_ENTRY_DOCUMENT_PATH = "https://s3.amazonaws.com/s3-ubetcoin-user-signatures/document/LEDGER-TO-LEDGER+ENTRY-FOR-UBETCOIN+03-20-2018.pdf"; string public constant UBETCOIN_LEDGER_TO_LEDGER_ENTRY_DOCUMENT_SHA512 = "c8f0ae2602005dd88ef908624cf59f3956107d0890d67d3baf9c885b64544a8140e282366cae6a3af7bfbc96d17f856b55fc4960e2287d4a03d67e646e0e88c6"; /// Base exchange rate is set uint256 public ratePerOneEther = 962; uint256 public totalUBetCheckAmounts = 0; /// Issue event index starting from 0. uint64 public issueIndex = 0; /// Emitted for each sucuessful token purchase. event Issue(uint64 issueIndex, address addr, uint256 tokenAmount); // All funds will be transferred in this wallet. address public moneyWallet = 0xe5688167Cb7aBcE4355F63943aAaC8bb269dc953; /// Emitted for each UBETCHECKS register. event UbetCheckIssue(string chequeIndex); struct UBetCheck { string accountId; string accountNumber; string fullName; string routingNumber; string institution; uint256 amount; uint256 tokens; string checkFilePath; string digitalCheckFingerPrint; } mapping (address => UBetCheck) UBetChecks; address[] public uBetCheckAccts; /// @dev Initializes the contract and allocates all initial tokens to the owner function UBetCoin() { balances[msg.sender] = totalSupply; } //////////////// owner only functions below /// @dev To transfer token contract ownership /// @param _newOwner The address of the new owner of this contract function transferOwnership(address _newOwner) onlyOwner { balances[_newOwner] = balances[owner]; balances[owner] = 0; Ownable.transferOwnership(_newOwner); } /// check functionality /// @dev Register UBetCheck to the chain /// @param _beneficiary recipient ether address /// @param _accountId the id generated from the db /// @param _accountNumber the account number stated in the check /// @param _routingNumber the routing number stated in the check /// @param _institution the name of the institution / bank in the check /// @param _fullname the name printed on the check /// @param _amount the amount in currency in the chek /// @param _checkFilePath the url path where the cheque has been uploaded /// @param _digitalCheckFingerPrint the hash of the file /// @param _tokens number of tokens issued to the beneficiary function registerUBetCheck(address _beneficiary, string _accountId, string _accountNumber, string _routingNumber, string _institution, string _fullname, uint256 _amount, string _checkFilePath, string _digitalCheckFingerPrint, uint256 _tokens) public payable onlyOwner { require(_beneficiary != address(0)); require(bytes(_accountId).length != 0); require(bytes(_accountNumber).length != 0); require(bytes(_routingNumber).length != 0); require(bytes(_institution).length != 0); require(bytes(_fullname).length != 0); require(_amount > 0); require(_tokens > 0); require(bytes(_checkFilePath).length != 0); require(bytes(_digitalCheckFingerPrint).length != 0); var __conToken = _tokens * (10**(decimals)); var uBetCheck = UBetChecks[_beneficiary]; uBetCheck.accountId = _accountId; uBetCheck.accountNumber = _accountNumber; uBetCheck.routingNumber = _routingNumber; uBetCheck.institution = _institution; uBetCheck.fullName = _fullname; uBetCheck.amount = _amount; uBetCheck.tokens = _tokens; uBetCheck.checkFilePath = _checkFilePath; uBetCheck.digitalCheckFingerPrint = _digitalCheckFingerPrint; totalUBetCheckAmounts = safeAdd(totalUBetCheckAmounts, _amount); tokenSupplyFromCheck = safeAdd(tokenSupplyFromCheck, _tokens); uBetCheckAccts.push(_beneficiary) -1; // Issue token when registered UBetCheck is complete to the _beneficiary doIssueTokens(_beneficiary, __conToken); // Fire Event UbetCheckIssue UbetCheckIssue(_accountId); } /// @dev List all the checks in the function getUBetChecks() public returns (address[]) { return uBetCheckAccts; } /// @dev Return UBetCheck information by supplying beneficiary adddress function getUBetCheck(address _address) public returns(string, string, string, string, uint256, string, string) { return (UBetChecks[_address].accountNumber, UBetChecks[_address].routingNumber, UBetChecks[_address].institution, UBetChecks[_address].fullName, UBetChecks[_address].amount, UBetChecks[_address].checkFilePath, UBetChecks[_address].digitalCheckFingerPrint); } /// @dev This default function allows token to be purchased by directly /// sending ether to this smart contract. function () public payable { purchaseTokens(msg.sender); } /// @dev return total count of registered UBet Checks function countUBetChecks() public returns (uint) { return uBetCheckAccts.length; } /// @dev issue tokens for a single buyer /// @param _beneficiary addresses that the tokens will be sent to. /// @param _tokens the amount of tokens, with decimals expanded (full). function doIssueTokens(address _beneficiary, uint256 _tokens) internal { require(_beneficiary != address(0)); // compute without actually increasing it uint256 increasedTotalSupply = safeAdd(totalSupply, _tokens); // increase token total supply totalSupply = increasedTotalSupply; // update the beneficiary balance to number of tokens sent balances[_beneficiary] = safeAdd(balances[_beneficiary], _tokens); Transfer(msg.sender, _beneficiary, _tokens); // event is fired when tokens issued Issue( issueIndex++, _beneficiary, _tokens ); } /// @dev Issue token based on Ether received. /// @param _beneficiary Address that newly issued token will be sent to. function purchaseTokens(address _beneficiary) public payable { // only accept a minimum amount of ETH? require(msg.value >= 0.00104 ether); uint _tokens = safeDiv(safeMul(msg.value, ratePerOneEther), (10**(18-decimals))); doIssueTokens(_beneficiary, _tokens); /// forward the money to the money wallet moneyWallet.transfer(this.balance); } /// @dev Change money wallet owner /// @param _address new address to received the ether function setMoneyWallet(address _address) public onlyOwner { moneyWallet = _address; } /// @dev Change Rate per token in one ether /// @param _value the amount of tokens, with decimals expanded (full). function setRatePerOneEther(uint256 _value) public onlyOwner { require(_value >= 1); ratePerOneEther = _value; } }
This default function allows token to be purchased by directly sending ether to this smart contract.
function () public payable { purchaseTokens(msg.sender); }
931,917
/* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { IController } from "../../interfaces/IController.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { Invoke } from "../lib/Invoke.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; import { Position } from "../lib/Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title AirdropModule * @author Set Protocol * * Module that enables managers to absorb tokens sent to the SetToken into the token's positions. With each SetToken, * managers are able to specify 1) the airdrops they want to include, 2) an airdrop fee recipient, 3) airdrop fee, * and 4) whether all users are allowed to trigger an airdrop. */ contract AirdropModule is ModuleBase, ReentrancyGuard { using PreciseUnitMath for uint256; using SafeMath for uint256; using Position for uint256; using SafeCast for int256; using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; /* ============ Structs ============ */ struct AirdropSettings { address[] airdrops; // Array of tokens manager is allowing to be absorbed address feeRecipient; // Address airdrop fees are sent to uint256 airdropFee; // Percentage in preciseUnits of airdrop sent to feeRecipient (1e16 = 1%) bool anyoneAbsorb; // Boolean indicating if any address can call absorb or just the manager } /* ============ Events ============ */ event ComponentAbsorbed( ISetToken indexed _setToken, address _absorbedToken, uint256 _absorbedQuantity, uint256 _managerFee, uint256 _protocolFee ); /* ============ Modifiers ============ */ /** * Throws if claim is confined to the manager and caller is not the manager */ modifier onlyValidCaller(ISetToken _setToken) { require(_isValidCaller(_setToken), "Must be valid caller"); _; } /* ============ Constants ============ */ uint256 public constant AIRDROP_MODULE_PROTOCOL_FEE_INDEX = 0; /* ============ State Variables ============ */ mapping(ISetToken => AirdropSettings) public airdropSettings; /* ============ Constructor ============ */ constructor(IController _controller) public ModuleBase(_controller) {} /* ============ External Functions ============ */ /** * Absorb passed tokens into respective positions. If airdropFee defined, send portion to feeRecipient and portion to * protocol feeRecipient address. Callable only by manager unless manager has set anyoneAbsorb to true. * * @param _setToken Address of SetToken * @param _tokens Array of tokens to absorb */ function batchAbsorb(ISetToken _setToken, address[] memory _tokens) external nonReentrant onlyValidCaller(_setToken) onlyValidAndInitializedSet(_setToken) { _batchAbsorb(_setToken, _tokens); } /** * Absorb specified token into position. If airdropFee defined, send portion to feeRecipient and portion to * protocol feeRecipient address. Callable only by manager unless manager has set anyoneAbsorb to true. * * @param _setToken Address of SetToken * @param _token Address of token to absorb */ function absorb(ISetToken _setToken, address _token) external nonReentrant onlyValidCaller(_setToken) onlyValidAndInitializedSet(_setToken) { _absorb(_setToken, _token); } /** * SET MANAGER ONLY. Adds new tokens to be added to positions when absorb is called. * * @param _setToken Address of SetToken * @param _airdrop List of airdrops to add */ function addAirdrop(ISetToken _setToken, address _airdrop) external onlyManagerAndValidSet(_setToken) { require(!isAirdropToken(_setToken, _airdrop), "Token already added."); airdropSettings[_setToken].airdrops.push(_airdrop); } /** * SET MANAGER ONLY. Removes tokens from list to be absorbed. * * @param _setToken Address of SetToken * @param _airdrop List of airdrops to remove */ function removeAirdrop(ISetToken _setToken, address _airdrop) external onlyManagerAndValidSet(_setToken) { require(isAirdropToken(_setToken, _airdrop), "Token not added."); airdropSettings[_setToken].airdrops = airdropSettings[_setToken].airdrops.remove(_airdrop); } /** * SET MANAGER ONLY. Update whether manager allows other addresses to call absorb. * * @param _setToken Address of SetToken */ function updateAnyoneAbsorb(ISetToken _setToken) external onlyManagerAndValidSet(_setToken) { airdropSettings[_setToken].anyoneAbsorb = !airdropSettings[_setToken].anyoneAbsorb; } /** * SET MANAGER ONLY. Update address manager fees are sent to. * * @param _setToken Address of SetToken * @param _newFeeRecipient Address of new fee recipient */ function updateFeeRecipient( ISetToken _setToken, address _newFeeRecipient ) external onlySetManager(_setToken, msg.sender) onlyValidAndInitializedSet(_setToken) { require(_newFeeRecipient != address(0), "Passed address must be non-zero"); airdropSettings[_setToken].feeRecipient = _newFeeRecipient; } /** * SET MANAGER ONLY. Update airdrop fee percentage. * * @param _setToken Address of SetToken * @param _newFee Percentage, in preciseUnits, of new airdrop fee (1e16 = 1%) */ function updateAirdropFee( ISetToken _setToken, uint256 _newFee ) external onlySetManager(_setToken, msg.sender) onlyValidAndInitializedSet(_setToken) { require(_newFee < PreciseUnitMath.preciseUnit(), "Airdrop fee can't exceed 100%"); // Absorb all outstanding tokens before fee is updated _batchAbsorb(_setToken, airdropSettings[_setToken].airdrops); airdropSettings[_setToken].airdropFee = _newFee; } /** * SET MANAGER ONLY. Initialize module with SetToken and set initial airdrop tokens as well as specify * whether anyone can call absorb. * * @param _setToken Address of SetToken * @param _airdropSettings Struct of airdrop setting for Set including accepted airdrops, feeRecipient, * airdropFee, and indicating if anyone can call an absorb */ function initialize( ISetToken _setToken, AirdropSettings memory _airdropSettings ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { require(_airdropSettings.airdrops.length > 0, "At least one token must be passed."); require(_airdropSettings.airdropFee <= PreciseUnitMath.preciseUnit(), "Fee must be <= 100%."); airdropSettings[_setToken] = _airdropSettings; _setToken.initializeModule(); } /** * Removes this module from the SetToken, via call by the SetToken. Token's airdrop settings are deleted. * Airdrops are not absorbed. */ function removeModule() external override { delete airdropSettings[ISetToken(msg.sender)]; } /** * Get list of tokens approved to collect airdrops for the SetToken. * * @param _setToken Address of SetToken * @return Array of tokens approved for airdrops */ function getAirdrops(ISetToken _setToken) external view returns (address[] memory) { return _airdrops(_setToken); } /** * Get boolean indicating if token is approved for airdrops. * * @param _setToken Address of SetToken * @return Boolean indicating approval for airdrops */ function isAirdropToken(ISetToken _setToken, address _token) public view returns (bool) { return _airdrops(_setToken).contains(_token); } /* ============ Internal Functions ============ */ /** * Check token approved for airdrops then handle airdropped postion. */ function _absorb(ISetToken _setToken, address _token) internal { require(isAirdropToken(_setToken, _token), "Must be approved token."); _handleAirdropPosition(_setToken, _token); } function _batchAbsorb(ISetToken _setToken, address[] memory _tokens) internal { for (uint256 i = 0; i < _tokens.length; i++) { _absorb(_setToken, _tokens[i]); } } /** * Calculate amount of tokens airdropped since last absorption, then distribute fees and update position. * * @param _setToken Address of SetToken * @param _token Address of airdropped token */ function _handleAirdropPosition(ISetToken _setToken, address _token) internal { uint256 preFeeTokenBalance = ERC20(_token).balanceOf(address(_setToken)); uint256 amountAirdropped = preFeeTokenBalance.sub(_setToken.getDefaultTrackedBalance(_token)); if (amountAirdropped > 0) { (uint256 managerTake, uint256 protocolTake, uint256 totalFees) = _handleFees(_setToken, _token, amountAirdropped); uint256 newUnit = _getPostAirdropUnit(_setToken, preFeeTokenBalance, totalFees); _setToken.editDefaultPosition(_token, newUnit); emit ComponentAbsorbed(_setToken, _token, amountAirdropped, managerTake, protocolTake); } } /** * Calculate fee total and distribute between feeRecipient defined on module and the protocol feeRecipient. * * @param _setToken Address of SetToken * @param _component Address of airdropped component * @param _amountAirdropped Amount of tokens airdropped to the SetToken * @return Amount of airdropped tokens set aside for manager fees * @return Amount of airdropped tokens set aside for protocol fees * @return Total fees paid */ function _handleFees( ISetToken _setToken, address _component, uint256 _amountAirdropped ) internal returns (uint256, uint256, uint256) { uint256 airdropFee = airdropSettings[_setToken].airdropFee; if (airdropFee > 0) { uint256 managerTake = _amountAirdropped.preciseMul(airdropFee); uint256 protocolTake = ModuleBase.getModuleFee(AIRDROP_MODULE_PROTOCOL_FEE_INDEX, managerTake); uint256 netManagerTake = managerTake.sub(protocolTake); uint256 totalFees = netManagerTake.add(protocolTake); _setToken.invokeTransfer(_component, airdropSettings[_setToken].feeRecipient, netManagerTake); ModuleBase.payProtocolFeeFromSetToken(_setToken, _component, protocolTake); return (netManagerTake, protocolTake, totalFees); } else { return (0, 0, 0); } } /** * Retrieve new unit, which is the current balance less fees paid divided by total supply */ function _getPostAirdropUnit( ISetToken _setToken, uint256 _totalComponentBalance, uint256 _totalFeesPaid ) internal view returns(uint256) { uint256 totalSupply = _setToken.totalSupply(); return totalSupply.getDefaultPositionUnit(_totalComponentBalance.sub(_totalFeesPaid)); } /** * If absorption is confined to the manager, manager must be caller */ function _isValidCaller(ISetToken _setToken) internal view returns(bool) { return airdropSettings[_setToken].anyoneAbsorb || isSetManager(_setToken, msg.sender); } function _airdrops(ISetToken _setToken) internal view returns(address[] memory) { return airdropSettings[_setToken].airdrops; } }
SET MANAGER ONLY. Initialize module with SetToken and set initial airdrop tokens as well as specify whether anyone can call absorb. _setToken Address of SetToken _airdropSettings Struct of airdrop setting for Set including accepted airdrops, feeRecipient, airdropFee, and indicating if anyone can call an absorb/
function initialize( ISetToken _setToken, AirdropSettings memory _airdropSettings ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { require(_airdropSettings.airdrops.length > 0, "At least one token must be passed."); require(_airdropSettings.airdropFee <= PreciseUnitMath.preciseUnit(), "Fee must be <= 100%."); airdropSettings[_setToken] = _airdropSettings; _setToken.initializeModule(); }
1,804,275
pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title 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; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } library Attribute { enum AttributeType { ROLE_MANAGER, // 0 ROLE_OPERATOR, // 1 IS_BLACKLISTED, // 2 HAS_PASSED_KYC_AML, // 3 NO_FEES, // 4 /* Additional user-defined later */ USER_DEFINED } function toUint256(AttributeType _type) internal pure returns (uint256) { return uint256(_type); } } /** * @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; } } library BitManipulation { uint256 constant internal ONE = uint256(1); function setBit(uint256 _num, uint256 _pos) internal pure returns (uint256) { return _num | (ONE << _pos); } function clearBit(uint256 _num, uint256 _pos) internal pure returns (uint256) { return _num & ~(ONE << _pos); } function toggleBit(uint256 _num, uint256 _pos) internal pure returns (uint256) { return _num ^ (ONE << _pos); } function checkBit(uint256 _num, uint256 _pos) internal pure returns (bool) { return (_num >> _pos & ONE == ONE); } } /** * @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 Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Claimable Ex * @dev Extension for the Claimable contract, where the ownership transfer can be canceled. */ contract ClaimableEx is Claimable { /* * @dev Cancels the ownership transfer. */ function cancelOwnershipTransfer() onlyOwner public { pendingOwner = owner; } } /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this Ether. * @notice Ether can still be sent to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ constructor() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by setting a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { owner.transfer(address(this).balance); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC223 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC223 compatible tokens * @param _from address The address that is transferring the tokens * @param _value uint256 the amount of the specified token * @param _data Bytes The data passed from the caller. */ function tokenFallback( address _from, uint256 _value, bytes _data ) external pure { _from; _value; _data; revert(); } } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param _contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address _contractAddr) external onlyOwner { Ownable contractInst = Ownable(_contractAddr); contractInst.transferOwnership(owner); } } /** * @title Base contract for contracts that should not own things. * @author Remco Bloemen <remco@2π.com> * @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or * Owned contracts. See respective base contracts for details. */ contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts { } /** * @title NoOwner Ex * @dev Extension for the NoOwner contract, to support a case where * this contract's owner can't own ether or tokens. * Note that we *do* inherit reclaimContract from NoOwner: This contract * does have to own contracts, but it also has to be able to relinquish them **/ contract NoOwnerEx is NoOwner { function reclaimEther(address _to) external onlyOwner { _to.transfer(address(this).balance); } function reclaimToken(ERC20Basic token, address _to) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(_to, balance); } } /** * @title Address Set. * @dev This contract allows to store addresses in a set and * owner can run a loop through all elements. **/ contract AddressSet is Ownable { mapping(address => bool) exist; address[] elements; /** * @dev Adds a new address to the set. * @param _addr Address to add. * @return True if succeed, otherwise false. */ function add(address _addr) onlyOwner public returns (bool) { if (contains(_addr)) { return false; } exist[_addr] = true; elements.push(_addr); return true; } /** * @dev Checks whether the set contains a specified address or not. * @param _addr Address to check. * @return True if the address exists in the set, otherwise false. */ function contains(address _addr) public view returns (bool) { return exist[_addr]; } /** * @dev Gets an element at a specified index in the set. * @param _index Index. * @return A relevant address. */ function elementAt(uint256 _index) onlyOwner public view returns (address) { require(_index < elements.length); return elements[_index]; } /** * @dev Gets the number of elements in the set. * @return The number of elements. */ function getTheNumberOfElements() onlyOwner public view returns (uint256) { return elements.length; } } // A wrapper around the balances mapping. contract BalanceSheet is ClaimableEx { using SafeMath for uint256; mapping (address => uint256) private balances; AddressSet private holderSet; constructor() public { holderSet = new AddressSet(); } /** * @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]; } function addBalance(address _addr, uint256 _value) public onlyOwner { balances[_addr] = balances[_addr].add(_value); _checkHolderSet(_addr); } function subBalance(address _addr, uint256 _value) public onlyOwner { balances[_addr] = balances[_addr].sub(_value); } function setBalance(address _addr, uint256 _value) public onlyOwner { balances[_addr] = _value; _checkHolderSet(_addr); } function setBalanceBatch( address[] _addrs, uint256[] _values ) public onlyOwner { uint256 _count = _addrs.length; require(_count == _values.length); for(uint256 _i = 0; _i < _count; _i++) { setBalance(_addrs[_i], _values[_i]); } } function getTheNumberOfHolders() public view returns (uint256) { return holderSet.getTheNumberOfElements(); } function getHolder(uint256 _index) public view returns (address) { return holderSet.elementAt(_index); } function _checkHolderSet(address _addr) internal { if (!holderSet.contains(_addr)) { holderSet.add(_addr); } } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * A version of OpenZeppelin's StandardToken whose balances mapping has been replaced * with a separate BalanceSheet contract. Most useful in combination with e.g. * HasNoContracts because then it can relinquish its balance sheet to a new * version of the token, removing the need to copy over balances. **/ contract StandardToken is ClaimableEx, NoOwnerEx, ERC20 { using SafeMath for uint256; uint256 totalSupply_; BalanceSheet private balances; event BalanceSheetSet(address indexed sheet); mapping (address => mapping (address => uint256)) private allowed; constructor() public { totalSupply_ = 0; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the 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.balanceOf(_owner); } /** * @dev Claim ownership of the BalanceSheet contract * @param _sheet The address of the BalanceSheet to claim. */ function setBalanceSheet(address _sheet) public onlyOwner returns (bool) { balances = BalanceSheet(_sheet); balances.claimOwnership(); emit BalanceSheetSet(_sheet); return true; } function getTheNumberOfHolders() public view returns (uint256) { return balances.getTheNumberOfHolders(); } function getHolder(uint256 _index) public view returns (address) { return balances.getHolder(_index); } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { _transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { _transferFrom(_from, _to, _value, msg.sender); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { _approve(_spender, _value, msg.sender); 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) * @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) { _increaseApproval(_spender, _addedValue, msg.sender); 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) * @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) { _decreaseApproval(_spender, _subtractedValue, msg.sender); return true; } function _approve( address _spender, uint256 _value, address _tokenHolder ) internal { allowed[_tokenHolder][_spender] = _value; emit Approval(_tokenHolder, _spender, _value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _burner The account whose tokens will be burnt. * @param _value The amount that will be burnt. */ function _burn(address _burner, uint256 _value) internal { require(_burner != 0); require(_value <= balanceOf(_burner), "not enough balance to burn"); // 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.subBalance(_burner, _value); totalSupply_ = totalSupply_.sub(_value); emit Transfer(_burner, address(0), _value); } function _decreaseApproval( address _spender, uint256 _subtractedValue, address _tokenHolder ) internal { uint256 _oldValue = allowed[_tokenHolder][_spender]; if (_subtractedValue >= _oldValue) { allowed[_tokenHolder][_spender] = 0; } else { allowed[_tokenHolder][_spender] = _oldValue.sub(_subtractedValue); } emit Approval(_tokenHolder, _spender, allowed[_tokenHolder][_spender]); } function _increaseApproval( address _spender, uint256 _addedValue, address _tokenHolder ) internal { allowed[_tokenHolder][_spender] = ( allowed[_tokenHolder][_spender].add(_addedValue)); emit Approval(_tokenHolder, _spender, allowed[_tokenHolder][_spender]); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances.addBalance(_account, _amount); emit Transfer(address(0), _account, _amount); } function _transfer(address _from, address _to, uint256 _value) internal { require(_to != address(0), "to address cannot be 0x0"); require(_from != address(0),"from address cannot be 0x0"); require(_value <= balanceOf(_from), "not enough balance to transfer"); // SafeMath.sub will throw if there is not enough balance. balances.subBalance(_from, _value); balances.addBalance(_to, _value); emit Transfer(_from, _to, _value); } function _transferFrom( address _from, address _to, uint256 _value, address _spender ) internal { uint256 _allowed = allowed[_from][_spender]; require(_value <= _allowed, "not enough allowance to transfer"); allowed[_from][_spender] = allowed[_from][_spender].sub(_value); _transfer(_from, _to, _value); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). **/ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value, string note); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. * @param _note a note that burner can attach. */ function burn(uint256 _value, string _note) public returns (bool) { _burn(msg.sender, _value, _note); return true; } /** * @dev Burns a specific amount of tokens of an user. * @param _burner Who has tokens to be burned. * @param _value The amount of tokens to be burned. * @param _note a note that the manager can attach. */ function _burn( address _burner, uint256 _value, string _note ) internal { _burn(_burner, _value); emit Burn(_burner, _value, _note); } } // Interface for logic governing write access to a Registry. contract RegistryAccessManager { // Called when _admin attempts to write _value for _who's _attribute. // Returns true if the write is allowed to proceed. function confirmWrite( address _who, Attribute.AttributeType _attribute, address _admin ) public returns (bool); } contract DefaultRegistryAccessManager is RegistryAccessManager { function confirmWrite( address /*_who*/, Attribute.AttributeType _attribute, address _operator ) public returns (bool) { Registry _client = Registry(msg.sender); if (_operator == _client.owner()) { return true; } else if (_client.hasAttribute(_operator, Attribute.AttributeType.ROLE_MANAGER)) { return (_attribute == Attribute.AttributeType.ROLE_OPERATOR); } else if (_client.hasAttribute(_operator, Attribute.AttributeType.ROLE_OPERATOR)) { return (_attribute != Attribute.AttributeType.ROLE_OPERATOR && _attribute != Attribute.AttributeType.ROLE_MANAGER); } } } contract Registry is ClaimableEx { using BitManipulation for uint256; struct AttributeData { uint256 value; } // Stores arbitrary attributes for users. An example use case is an ERC20 // token that requires its users to go through a KYC/AML check - in this case // a validator can set an account's "hasPassedKYC/AML" attribute to 1 to indicate // that account can use the token. This mapping stores that value (1, in the // example) as well as which validator last set the value and at what time, // so that e.g. the check can be renewed at appropriate intervals. mapping(address => AttributeData) private attributes; // The logic governing who is allowed to set what attributes is abstracted as // this accessManager, so that it may be replaced by the owner as needed. RegistryAccessManager public accessManager; event SetAttribute( address indexed who, Attribute.AttributeType attribute, bool enable, string notes, address indexed adminAddr ); event SetManager( address indexed oldManager, address indexed newManager ); constructor() public { accessManager = new DefaultRegistryAccessManager(); } // Writes are allowed only if the accessManager approves function setAttribute( address _who, Attribute.AttributeType _attribute, string _notes ) public { bool _canWrite = accessManager.confirmWrite( _who, _attribute, msg.sender ); require(_canWrite); // Get value of previous attribute before setting new attribute uint256 _tempVal = attributes[_who].value; attributes[_who] = AttributeData( _tempVal.setBit(Attribute.toUint256(_attribute)) ); emit SetAttribute(_who, _attribute, true, _notes, msg.sender); } function clearAttribute( address _who, Attribute.AttributeType _attribute, string _notes ) public { bool _canWrite = accessManager.confirmWrite( _who, _attribute, msg.sender ); require(_canWrite); // Get value of previous attribute before setting new attribute uint256 _tempVal = attributes[_who].value; attributes[_who] = AttributeData( _tempVal.clearBit(Attribute.toUint256(_attribute)) ); emit SetAttribute(_who, _attribute, false, _notes, msg.sender); } // Returns true if the uint256 value stored for this attribute is non-zero function hasAttribute( address _who, Attribute.AttributeType _attribute ) public view returns (bool) { return attributes[_who].value.checkBit(Attribute.toUint256(_attribute)); } // Returns the exact value of the attribute, as well as its metadata function getAttributes( address _who ) public view returns (uint256) { AttributeData memory _data = attributes[_who]; return _data.value; } function setManager(RegistryAccessManager _accessManager) public onlyOwner { emit SetManager(accessManager, _accessManager); accessManager = _accessManager; } } // Superclass for contracts that have a registry that can be set by their owners contract HasRegistry is Ownable { Registry public registry; event SetRegistry(address indexed registry); function setRegistry(Registry _registry) public onlyOwner { registry = _registry; emit SetRegistry(registry); } } /** * @title Manageable * @dev The Manageable contract provides basic authorization control functions * for managers. This simplifies the implementation of "manager permissions". */ contract Manageable is HasRegistry { /** * @dev Throws if called by any account that is not in the managers list. */ modifier onlyManager() { require( registry.hasAttribute( msg.sender, Attribute.AttributeType.ROLE_MANAGER ) ); _; } /** * @dev Getter to determine if address is a manager */ function isManager(address _operator) public view returns (bool) { return registry.hasAttribute( _operator, Attribute.AttributeType.ROLE_MANAGER ); } } // Interface implemented by tokens that are the *target* of a BurnableToken's // delegation. That is, if we want to replace BurnableToken X by // Y but for convenience we'd like users of X // to be able to keep using it and it will just forward calls to Y, // then X should extend CanDelegate and Y should extend DelegateBurnable. // Most ERC20 calls use the value of msg.sender to figure out e.g. whose // balance to update; since X becomes the msg.sender of all such calls // that it forwards to Y, we add the origSender parameter to those calls. // Delegation is intended as a convenience for legacy users of X since // we do not expect all regular users to learn about Y and change accordingly, // but we do require the *owner* of X to now use Y instead so ownerOnly // functions are not delegated and should be disabled instead. // This delegation system is intended to work with the modified versions of // the standard ERC20 token contracts, allowing the balances // to be moved over to a new contract. // NOTE: To maintain backwards compatibility, these function signatures // cannot be changed contract DelegateBurnable { function delegateTotalSupply() public view returns (uint256); function delegateBalanceOf(address _who) public view returns (uint256); function delegateTransfer(address _to, uint256 _value, address _origSender) public returns (bool); function delegateAllowance(address _owner, address _spender) public view returns (uint256); function delegateTransferFrom( address _from, address _to, uint256 _value, address _origSender ) public returns (bool); function delegateApprove( address _spender, uint256 _value, address _origSender ) public returns (bool); function delegateIncreaseApproval( address _spender, uint256 _addedValue, address _origSender ) public returns (bool); function delegateDecreaseApproval( address _spender, uint256 _subtractedValue, address _origSender ) public returns (bool); function delegateBurn( address _origSender, uint256 _value, string _note ) public; function delegateGetTheNumberOfHolders() public view returns (uint256); function delegateGetHolder(uint256 _index) public view returns (address); } /** * @title Contactable token * @dev Basic version of a contactable contract, allowing the owner to provide a string with their * contact information. */ contract Contactable is Ownable { string public contactInformation; /** * @dev Allows the owner to set a string with their contact information. * @param _info The contact information to attach to the contract. */ function setContactInformation(string _info) public onlyOwner { contactInformation = _info; } } /** * @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() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function _transfer( address _from, address _to, uint256 _value ) internal whenNotPaused { super._transfer(_from, _to, _value); } function _transferFrom( address _from, address _to, uint256 _value, address _spender ) internal whenNotPaused { super._transferFrom(_from, _to, _value, _spender); } function _approve( address _spender, uint256 _value, address _tokenHolder ) internal whenNotPaused { super._approve(_spender, _value, _tokenHolder); } function _increaseApproval( address _spender, uint256 _addedValue, address _tokenHolder ) internal whenNotPaused { super._increaseApproval(_spender, _addedValue, _tokenHolder); } function _decreaseApproval( address _spender, uint256 _subtractedValue, address _tokenHolder ) internal whenNotPaused { super._decreaseApproval(_spender, _subtractedValue, _tokenHolder); } function _burn( address _burner, uint256 _value ) internal whenNotPaused { super._burn(_burner, _value); } } // See DelegateBurnable.sol for more on the delegation system. contract CanDelegateToken is BurnableToken { // If this contract needs to be upgraded, the new contract will be stored // in 'delegate' and any BurnableToken calls to this contract will be delegated to that one. DelegateBurnable public delegate; event DelegateToNewContract(address indexed newContract); // Can undelegate by passing in _newContract = address(0) function delegateToNewContract( DelegateBurnable _newContract ) public onlyOwner { delegate = _newContract; emit DelegateToNewContract(delegate); } // If a delegate has been designated, all ERC20 calls are forwarded to it function _transfer(address _from, address _to, uint256 _value) internal { if (!_hasDelegate()) { super._transfer(_from, _to, _value); } else { require(delegate.delegateTransfer(_to, _value, _from)); } } function _transferFrom( address _from, address _to, uint256 _value, address _spender ) internal { if (!_hasDelegate()) { super._transferFrom(_from, _to, _value, _spender); } else { require(delegate.delegateTransferFrom(_from, _to, _value, _spender)); } } function totalSupply() public view returns (uint256) { if (!_hasDelegate()) { return super.totalSupply(); } else { return delegate.delegateTotalSupply(); } } function balanceOf(address _who) public view returns (uint256) { if (!_hasDelegate()) { return super.balanceOf(_who); } else { return delegate.delegateBalanceOf(_who); } } function getTheNumberOfHolders() public view returns (uint256) { if (!_hasDelegate()) { return super.getTheNumberOfHolders(); } else { return delegate.delegateGetTheNumberOfHolders(); } } function getHolder(uint256 _index) public view returns (address) { if (!_hasDelegate()) { return super.getHolder(_index); } else { return delegate.delegateGetHolder(_index); } } function _approve( address _spender, uint256 _value, address _tokenHolder ) internal { if (!_hasDelegate()) { super._approve(_spender, _value, _tokenHolder); } else { require(delegate.delegateApprove(_spender, _value, _tokenHolder)); } } function allowance( address _owner, address _spender ) public view returns (uint256) { if (!_hasDelegate()) { return super.allowance(_owner, _spender); } else { return delegate.delegateAllowance(_owner, _spender); } } function _increaseApproval( address _spender, uint256 _addedValue, address _tokenHolder ) internal { if (!_hasDelegate()) { super._increaseApproval(_spender, _addedValue, _tokenHolder); } else { require( delegate.delegateIncreaseApproval(_spender, _addedValue, _tokenHolder) ); } } function _decreaseApproval( address _spender, uint256 _subtractedValue, address _tokenHolder ) internal { if (!_hasDelegate()) { super._decreaseApproval(_spender, _subtractedValue, _tokenHolder); } else { require( delegate.delegateDecreaseApproval( _spender, _subtractedValue, _tokenHolder) ); } } function _burn(address _burner, uint256 _value, string _note) internal { if (!_hasDelegate()) { super._burn(_burner, _value, _note); } else { delegate.delegateBurn(_burner, _value , _note); } } function _hasDelegate() internal view returns (bool) { return !(delegate == address(0)); } } // Treats all delegate functions exactly like the corresponding normal functions, // e.g. delegateTransfer is just like transfer. See DelegateBurnable.sol for more on // the delegation system. contract DelegateToken is DelegateBurnable, BurnableToken { address public delegatedFrom; event DelegatedFromSet(address addr); // Only calls from appointed address will be processed modifier onlyMandator() { require(msg.sender == delegatedFrom); _; } function setDelegatedFrom(address _addr) public onlyOwner { delegatedFrom = _addr; emit DelegatedFromSet(_addr); } // each function delegateX is simply forwarded to function X function delegateTotalSupply( ) public onlyMandator view returns (uint256) { return totalSupply(); } function delegateBalanceOf( address _who ) public onlyMandator view returns (uint256) { return balanceOf(_who); } function delegateTransfer( address _to, uint256 _value, address _origSender ) public onlyMandator returns (bool) { _transfer(_origSender, _to, _value); return true; } function delegateAllowance( address _owner, address _spender ) public onlyMandator view returns (uint256) { return allowance(_owner, _spender); } function delegateTransferFrom( address _from, address _to, uint256 _value, address _origSender ) public onlyMandator returns (bool) { _transferFrom(_from, _to, _value, _origSender); return true; } function delegateApprove( address _spender, uint256 _value, address _origSender ) public onlyMandator returns (bool) { _approve(_spender, _value, _origSender); return true; } function delegateIncreaseApproval( address _spender, uint256 _addedValue, address _origSender ) public onlyMandator returns (bool) { _increaseApproval(_spender, _addedValue, _origSender); return true; } function delegateDecreaseApproval( address _spender, uint256 _subtractedValue, address _origSender ) public onlyMandator returns (bool) { _decreaseApproval(_spender, _subtractedValue, _origSender); return true; } function delegateBurn( address _origSender, uint256 _value, string _note ) public onlyMandator { _burn(_origSender, _value , _note); } function delegateGetTheNumberOfHolders() public view returns (uint256) { return getTheNumberOfHolders(); } function delegateGetHolder(uint256 _index) public view returns (address) { return getHolder(_index); } } /** * @title Asset information. * @dev Stores information about a specified real asset. */ contract AssetInfo is Manageable { string public publicDocument; /** * Event for updated running documents logging. * @param newLink New link. */ event UpdateDocument( string newLink ); /** * @param _publicDocument A link to a zip file containing running documents of the asset. */ constructor(string _publicDocument) public { publicDocument = _publicDocument; } /** * @dev Updates information about where to find new running documents of this asset. * @param _link A link to a zip file containing running documents of the asset. */ function setPublicDocument(string _link) public onlyManager { publicDocument = _link; emit UpdateDocument(publicDocument); } } /** * @title BurnableExToken. * @dev Extension for the BurnableToken contract, to support * some manager to enforce burning all tokens of all holders. **/ contract BurnableExToken is Manageable, BurnableToken { /** * @dev Burns all remaining tokens of all holders. * @param _note a note that the manager can attach. */ function burnAll(string _note) external onlyManager { uint256 _holdersCount = getTheNumberOfHolders(); for (uint256 _i = 0; _i < _holdersCount; ++_i) { address _holder = getHolder(_i); uint256 _balance = balanceOf(_holder); if (_balance == 0) continue; _burn(_holder, _balance, _note); } } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation **/ contract MintableToken is StandardToken { event Mint(address indexed to, uint256 value); 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 _value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _value ) public hasMintPermission canMint returns (bool) { _mint(_to, _value); emit Mint(_to, _value); 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; } } contract CompliantToken is HasRegistry, MintableToken { // Addresses can also be blacklisted, preventing them from sending or receiving // PAT tokens. This can be used to prevent the use of PAT by bad actors in // accordance with law enforcement. modifier onlyIfNotBlacklisted(address _addr) { require( !registry.hasAttribute( _addr, Attribute.AttributeType.IS_BLACKLISTED ) ); _; } modifier onlyIfBlacklisted(address _addr) { require( registry.hasAttribute( _addr, Attribute.AttributeType.IS_BLACKLISTED ) ); _; } modifier onlyIfPassedKYC_AML(address _addr) { require( registry.hasAttribute( _addr, Attribute.AttributeType.HAS_PASSED_KYC_AML ) ); _; } function _mint( address _to, uint256 _value ) internal onlyIfPassedKYC_AML(_to) onlyIfNotBlacklisted(_to) { super._mint(_to, _value); } // transfer and transferFrom both call this function, so check blacklist here. function _transfer( address _from, address _to, uint256 _value ) internal onlyIfNotBlacklisted(_from) onlyIfNotBlacklisted(_to) onlyIfPassedKYC_AML(_to) { super._transfer(_from, _to, _value); } } /** * @title TokenWithFees. * @dev This contract allows for transaction fees to be assessed on transfer. **/ contract TokenWithFees is Manageable, StandardToken { uint8 public transferFeeNumerator = 0; uint8 public transferFeeDenominator = 100; // All transaction fees are paid to this address. address public beneficiary; event ChangeWallet(address indexed addr); event ChangeFees(uint8 transferFeeNumerator, uint8 transferFeeDenominator); constructor(address _wallet) public { beneficiary = _wallet; } // transfer and transferFrom both call this function, so pay fee here. // E.g. if A transfers 1000 tokens to B, B will receive 999 tokens, // and the system wallet will receive 1 token. function _transfer(address _from, address _to, uint256 _value) internal { uint256 _fee = _payFee(_from, _value, _to); uint256 _remaining = _value.sub(_fee); super._transfer(_from, _to, _remaining); } function _payFee( address _payer, uint256 _value, address _otherParticipant ) internal returns (uint256) { // This check allows accounts to be whitelisted and not have to pay transaction fees. bool _shouldBeFree = ( registry.hasAttribute(_payer, Attribute.AttributeType.NO_FEES) || registry.hasAttribute(_otherParticipant, Attribute.AttributeType.NO_FEES) ); if (_shouldBeFree) { return 0; } uint256 _fee = _value.mul(transferFeeNumerator).div(transferFeeDenominator); if (_fee > 0) { super._transfer(_payer, beneficiary, _fee); } return _fee; } function checkTransferFee(uint256 _value) public view returns (uint256) { return _value.mul(transferFeeNumerator).div(transferFeeDenominator); } function changeFees( uint8 _transferFeeNumerator, uint8 _transferFeeDenominator ) public onlyManager { require(_transferFeeNumerator < _transferFeeDenominator); transferFeeNumerator = _transferFeeNumerator; transferFeeDenominator = _transferFeeDenominator; emit ChangeFees(transferFeeNumerator, transferFeeDenominator); } /** * @dev Change address of the wallet where the fees will be sent to. * @param _beneficiary The new wallet address. */ function changeWallet(address _beneficiary) public onlyManager { require(_beneficiary != address(0), "new wallet cannot be 0x0"); beneficiary = _beneficiary; emit ChangeWallet(_beneficiary); } } // This allows a token to treat transfer(redeemAddress, value) as burn(value). // This is useful for users of standard wallet programs which have transfer // functionality built in but not the ability to burn. contract WithdrawalToken is BurnableToken { address public constant redeemAddress = 0xfacecafe01facecafe02facecafe03facecafe04; function _transfer(address _from, address _to, uint256 _value) internal { if (_to == redeemAddress) { burn(_value, ''); } else { super._transfer(_from, _to, _value); } } // StandardToken's transferFrom doesn't have to check for _to != redeemAddress, // but we do because we redirect redeemAddress transfers to burns, but // we do not redirect transferFrom function _transferFrom( address _from, address _to, uint256 _value, address _spender ) internal { require(_to != redeemAddress, "_to is redeem address"); super._transferFrom(_from, _to, _value, _spender); } } /** * @title PAT token. * @dev PAT is a ERC20 token that: * - has no tokens limit. * - mints new tokens for each new property (real asset). * - can pause and unpause token transfer (and authorization) actions. * - token holders can be distributed profit from asset manager. * - contains real asset information. * - can delegate to a new contract. * - can enforce burning all tokens. * - transferring tokens to 0x0 address is treated as burning. * - transferring tokens with fees are sent to the system wallet. * - attempts to check KYC/AML and Blacklist using Registry. * - attempts to reject ERC20 token transfers to itself and allows token transfer out. * - attempts to reject ether sent and allows any ether held to be transferred out. * - allows the new owner to accept the ownership transfer, the owner can cancel the transfer if needed. **/ contract PATToken is Contactable, AssetInfo, BurnableExToken, CanDelegateToken, DelegateToken, TokenWithFees, CompliantToken, WithdrawalToken, PausableToken { string public name = "RAX Mt.Fuji"; string public symbol = "FUJI"; uint8 public constant decimals = 18; event ChangeTokenName(string newName, string newSymbol); /** * @param _name Name of this token. * @param _symbol Symbol of this token. */ constructor( string _name, string _symbol, string _publicDocument, address _wallet ) public AssetInfo(_publicDocument) TokenWithFees(_wallet) { name = _name; symbol = _symbol; contactInformation = 'https://rax.exchange/'; } function changeTokenName(string _name, string _symbol) public onlyOwner { name = _name; symbol = _symbol; emit ChangeTokenName(_name, _symbol); } /** * @dev Allows the current owner to transfer control of the contract to a new owner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) onlyOwner public { // do not allow self ownership require(_newOwner != address(this)); super.transferOwnership(_newOwner); } }
Internal function that mints an amount of the token and assigns it to an account. This encapsulates the modification of balances such that the proper events are emitted. _account The account that will receive the created tokens. _amount The amount that will be created./
function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances.addBalance(_account, _amount); emit Transfer(address(0), _account, _amount); }
13,059,875
pragma solidity ^0.4.18; // 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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @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(); } } // File: openzeppelin-solidity/contracts/ownership/HasNoEther.sol /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be send to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } // File: contracts/TweedentityManager.sol interface ITweedentityStore { function isUpgradable(address _address, string _uid) public constant returns (bool); function setIdentity(address _address, string _uid) external; function unsetIdentity(address _address) external; function getAppNickname() external constant returns (bytes32); function getAppId() external constant returns (uint); function getAddressLastUpdate(address _address) external constant returns (uint); function isUid(string _uid) public pure returns (bool); } /** * @title TweedentityManager * @author Francesco Sullo <[email protected]> * @dev Sets and removes tweedentities in the store, * adding more logic to the simple logic of the store */ contract TweedentityManager is Pausable, HasNoEther { string public version = "1.3.0"; struct Store { ITweedentityStore store; address addr; } mapping(uint => Store) private __stores; mapping(uint => bytes32) public appNicknames32; mapping(uint => string) public appNicknames; mapping(string => uint) private __appIds; address public claimer; address public newClaimer; mapping(address => bool) public customerService; address[] private __customerServiceAddress; uint public upgradable = 0; uint public notUpgradableInStore = 1; uint public addressNotUpgradable = 2; uint public minimumTimeBeforeUpdate = 1 hours; // events event IdentityNotUpgradable( string appNickname, address indexed addr, string uid ); // config /** * @dev Sets a store to be used by the manager * @param _appNickname The nickname of the app for which the store&#39;s been configured * @param _address The address of the store */ function setAStore( string _appNickname, address _address ) public onlyOwner { require(bytes(_appNickname).length > 0); bytes32 _appNickname32 = keccak256(_appNickname); require(_address != address(0)); ITweedentityStore _store = ITweedentityStore(_address); require(_store.getAppNickname() == _appNickname32); uint _appId = _store.getAppId(); require(appNicknames32[_appId] == 0x0); appNicknames32[_appId] = _appNickname32; appNicknames[_appId] = _appNickname; __appIds[_appNickname] = _appId; __stores[_appId] = Store( ITweedentityStore(_address), _address ); } /** * @dev Sets the claimer which will verify the ownership and call to set a tweedentity * @param _address Address of the claimer */ function setClaimer( address _address ) public onlyOwner { require(_address != address(0)); claimer = _address; } /** * @dev Sets a new claimer during updates * @param _address Address of the new claimer */ function setNewClaimer( address _address ) public onlyOwner { require(_address != address(0) && claimer != address(0)); newClaimer = _address; } /** * @dev Sets new manager */ function switchClaimerAndRemoveOldOne() external onlyOwner { claimer = newClaimer; newClaimer = address(0); } /** * @dev Sets a wallet as customer service to perform emergency removal of wrong, abused, squatted tweedentities (due, for example, to hacking of the Twitter account) * @param _address The customer service wallet * @param _status The status (true is set, false is unset) */ function setCustomerService( address _address, bool _status ) public onlyOwner { require(_address != address(0)); customerService[_address] = _status; bool found; for (uint i = 0; i < __customerServiceAddress.length; i++) { if (__customerServiceAddress[i] == _address) { found = true; break; } } if (!found) { __customerServiceAddress.push(_address); } } //modifiers modifier onlyClaimer() { require(msg.sender == claimer || (newClaimer != address(0) && msg.sender == newClaimer)); _; } modifier onlyCustomerService() { require(msg.sender == owner || customerService[msg.sender] == true); _; } modifier whenStoreSet( uint _appId ) { require(appNicknames32[_appId] != 0x0); _; } // internal getters function __getStore( uint _appId ) internal constant returns (ITweedentityStore) { return __stores[_appId].store; } // helpers function isAddressUpgradable( ITweedentityStore _store, address _address ) internal constant returns (bool) { uint lastUpdate = _store.getAddressLastUpdate(_address); return lastUpdate == 0 || now >= lastUpdate + minimumTimeBeforeUpdate; } function isUpgradable( ITweedentityStore _store, address _address, string _uid ) internal constant returns (bool) { if (!_store.isUpgradable(_address, _uid) || !isAddressUpgradable(_store, _address)) { return false; } return true; } // getters /** * @dev Gets the app-id associated to a nickname * @param _appNickname The nickname of a configured app */ function getAppId( string _appNickname ) external constant returns (uint) { return __appIds[_appNickname]; } /** * @dev Allows other contracts to check if a store is set * @param _appNickname The nickname of a configured app */ function isStoreSet( string _appNickname ) public constant returns (bool){ return __appIds[_appNickname] != 0; } /** * @dev Return a numeric code about the upgradability of a couple wallet-uid in a certain app * @param _appId The id of the app * @param _address The address of the wallet * @param _uid The user-id */ function getUpgradability( uint _appId, address _address, string _uid ) external constant returns (uint) { ITweedentityStore _store = __getStore(_appId); if (!_store.isUpgradable(_address, _uid)) { return notUpgradableInStore; } else if (!isAddressUpgradable(_store, _address)) { return addressNotUpgradable; } else { return upgradable; } } /** * @dev Returns the address of a store * @param _appNickname The app nickname */ function getStoreAddress( string _appNickname ) external constant returns (address) { return __stores[__appIds[_appNickname]].addr; } /** * @dev Returns the address of any customerService account */ function getCustomerServiceAddress() external constant returns (address[]) { return __customerServiceAddress; } // primary methods /** * @dev Sets a new identity * @param _appId The id of the app * @param _address The address of the wallet * @param _uid The user-id */ function setIdentity( uint _appId, address _address, string _uid ) external onlyClaimer whenStoreSet(_appId) whenNotPaused { require(_address != address(0)); ITweedentityStore _store = __getStore(_appId); require(_store.isUid(_uid)); if (isUpgradable(_store, _address, _uid)) { _store.setIdentity(_address, _uid); } else { IdentityNotUpgradable(appNicknames[_appId], _address, _uid); } } /** * @dev Unsets an existent identity * @param _appId The id of the app * @param _address The address of the wallet */ function unsetIdentity( uint _appId, address _address ) external onlyCustomerService whenStoreSet(_appId) whenNotPaused { ITweedentityStore _store = __getStore(_appId); _store.unsetIdentity(_address); } /** * @dev Allow the sender to unset its existent identity * @param _appId The id of the app */ function unsetMyIdentity( uint _appId ) external whenStoreSet(_appId) whenNotPaused { ITweedentityStore _store = __getStore(_appId); _store.unsetIdentity(msg.sender); } /** * @dev Update the minimum time before allowing a wallet to update its data * @param _newMinimumTime The new minimum time in seconds */ function changeMinimumTimeBeforeUpdate( uint _newMinimumTime ) external onlyOwner { minimumTimeBeforeUpdate = _newMinimumTime; } // private methods function __stringToUint( string s ) internal pure returns (uint result) { bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i++) { uint c = uint(b[i]); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); } } } function __uintToBytes(uint x) internal pure returns (bytes b) { b = new bytes(32); for (uint i = 0; i < 32; i++) { b[i] = byte(uint8(x / (2 ** (8 * (31 - i))))); } } }
Sets new manager/
function switchClaimerAndRemoveOldOne() external onlyOwner { claimer = newClaimer; newClaimer = address(0); }
7,631,619
./full_match/43114/0xAE6FC6f56e8440E6429c5bEB851Ca864495849Bf/sources/EthBondDepository.sol
allow user to stake payout automatically _stake bool _amount uint return uint/
function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) { IERC20( N3RV ).approve( stakingHelper, _amount ); IStakingHelper( stakingHelper ).stake( _amount, _recipient ); IERC20( N3RV ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient ); } else { }
4,517,164
./partial_match/1/0xcE681ef76Ac8DF6E7b545a9244Ee9C6a6E82Cc53/sources/MinosGlobalStage1.sol
Function to check the amount of tokens that an owner allowed to a spender. owner address The address which owns the funds. 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 ) external view override returns (uint256) { return allowed[owner][spender]; }
2,658,047
./partial_match/1/0xf355811f4c8117E73a9F0A1b5769c123b8b5E31A/sources/contracts/XSD/XSDStablecoin.sol
This function is what other xsd pools will call to mint new XSD
function pool_mint(address m_address, uint256 m_amount) public onlyPools { super._mint(m_address, m_amount); emit XSDMinted(msg.sender, m_address, m_amount); }
4,399,035
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; interface IUniswapV2Factory { event PAIRCREATED765(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO173() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER947() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR540(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS330(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH28() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR870(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO87(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER308(address) external; //inject NONSTANDARD NAMING } interface IUniswapV2Pair { event APPROVAL174(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER306(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME472() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL588() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS125() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY849() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF412(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE690(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE763(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER680(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM721(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR798() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH5() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES780(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT824(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT900(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN945(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP468( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC111(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY386() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY86() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0481() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1550() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES473() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST512() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST431() external view returns (uint); //inject NONSTANDARD NAMING function KLAST25() external view returns (uint); //inject NONSTANDARD NAMING function MINT371(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN742(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP14(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM245(address to) external; //inject NONSTANDARD NAMING function SYNC404() external; //inject NONSTANDARD NAMING function INITIALIZE744(address, address) external; //inject NONSTANDARD NAMING } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant resolution65 = 112; //inject NONSTANDARD NAMING // encode a uint112 as a UQ112x112 function ENCODE953(uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING return uq112x112(uint224(x) << resolution65); } // encodes a uint144 as a UQ144x112 function ENCODE144474(uint144 x) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING return uq144x112(uint256(x) << resolution65); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function DIV758(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function MUL709(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function FRACTION20(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << resolution65) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function DECODE642(uq112x112 memory self) internal pure returns (uint112) { //inject NONSTANDARD NAMING return uint112(self._x >> resolution65); } // decode a UQ144x112 into a uint144 by truncating after the radix point function DECODE144805(uq144x112 memory self) internal pure returns (uint144) { //inject NONSTANDARD NAMING return uint144(self._x >> resolution65); } } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function CURRENTBLOCKTIMESTAMP616() internal view returns (uint32) { //inject NONSTANDARD NAMING return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function CURRENTCUMULATIVEPRICES565( //inject NONSTANDARD NAMING address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = CURRENTBLOCKTIMESTAMP616(); price0Cumulative = IUniswapV2Pair(pair).PRICE0CUMULATIVELAST512(); price1Cumulative = IUniswapV2Pair(pair).PRICE1CUMULATIVELAST431(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).GETRESERVES473(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.FRACTION20(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.FRACTION20(reserve0, reserve1)._x) * timeElapsed; } } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function ADD508(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function ADD508(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, errorMessage); return c; } function SUB277(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB277(a, b, "SafeMath: subtraction underflow"); } function SUB277(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL709(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function MUL709(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function DIV758(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV758(a, b, "SafeMath: division by zero"); } function DIV758(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD92(a, b, "SafeMath: modulo by zero"); } function MOD92(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function SORTTOKENS379(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //inject NONSTANDARD NAMING require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function PAIRFOR87(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING (address token0, address token1) = SORTTOKENS379(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function GETRESERVES473(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { //inject NONSTANDARD NAMING (address token0,) = SORTTOKENS379(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(PAIRFOR87(factory, tokenA, tokenB)).GETRESERVES473(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function QUOTE2(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { //inject NONSTANDARD NAMING require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.MUL709(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function GETAMOUNTOUT789(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { //inject NONSTANDARD NAMING require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.MUL709(997); uint numerator = amountInWithFee.MUL709(reserveOut); uint denominator = reserveIn.MUL709(1000).ADD508(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function GETAMOUNTIN163(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { //inject NONSTANDARD NAMING require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.MUL709(amountOut).MUL709(1000); uint denominator = reserveOut.SUB277(amountOut).MUL709(997); amountIn = (numerator / denominator).ADD508(1); } // performs chained getAmountOut calculations on any number of pairs function GETAMOUNTSOUT330(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = GETRESERVES473(factory, path[i], path[i + 1]); amounts[i + 1] = GETAMOUNTOUT789(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function GETAMOUNTSIN267(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = GETRESERVES473(factory, path[i - 1], path[i]); amounts[i - 1] = GETAMOUNTIN163(amounts[i], reserveIn, reserveOut); } } } interface WETH9 { function WITHDRAW840(uint wad) external; //inject NONSTANDARD NAMING } interface IUniswapV2Router { function SWAPEXACTTOKENSFORTOKENS109( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } interface IKeep3rV1 { function ISMINKEEPER913(address keeper, uint minBond, uint earned, uint age) external returns (bool); //inject NONSTANDARD NAMING function RECEIPT100(address credit, address keeper, uint amount) external; //inject NONSTANDARD NAMING function UNBOND169(address bonding, uint amount) external; //inject NONSTANDARD NAMING function WITHDRAW840(address bonding) external; //inject NONSTANDARD NAMING function BONDS570(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING function UNBONDINGS996(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE763(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function JOBS817(address job) external view returns (bool); //inject NONSTANDARD NAMING function BALANCEOF412(address account) external view returns (uint256); //inject NONSTANDARD NAMING function WORKED219(address keeper) external; //inject NONSTANDARD NAMING function KPRH771() external view returns (IKeep3rV1Helper); //inject NONSTANDARD NAMING } interface IKeep3rV1Helper { function GETQUOTELIMIT880(uint gasUsed) external view returns (uint); //inject NONSTANDARD NAMING } // sliding oracle that uses observations collected to provide moving price averages in the past contract YearnV2Oracle { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; } uint public minKeep = 200e18; modifier KEEPER983() { //inject NONSTANDARD NAMING require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; } modifier UPKEEP664() { //inject NONSTANDARD NAMING uint _gasUsed = gasleft(); require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; uint _received = kp3r674.KPRH771().GETQUOTELIMIT880(_gasUsed.SUB277(gasleft())); kp3r674.RECEIPT100(address(kp3r674), address(this), _received); _received = _SWAP523(_received); msg.sender.transfer(_received); } address public governance; address public pendingGovernance; function SETMINKEEP842(uint _keep) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setGovernance: !gov"); minKeep = _keep; } function SETGOVERNANCE949(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } function ACCEPTGOVERNANCE56() external { //inject NONSTANDARD NAMING require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } IKeep3rV1 public constant kp3r674 = IKeep3rV1(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44); //inject NONSTANDARD NAMING WETH9 public constant weth411 = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING IUniswapV2Router public constant uni703 = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING address public constant factory868 = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; //inject NONSTANDARD NAMING // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint public constant periodsize934 = 1800; //inject NONSTANDARD NAMING address[] internal _pairs; mapping(address => bool) internal _known; function PAIRS458() external view returns (address[] memory) { //inject NONSTANDARD NAMING return _pairs; } mapping(address => Observation[]) public observations; function OBSERVATIONLENGTH959(address pair) external view returns (uint) { //inject NONSTANDARD NAMING return observations[pair].length; } function PAIRFOR87(address tokenA, address tokenB) external pure returns (address) { //inject NONSTANDARD NAMING return UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); } function PAIRFORWETH375(address tokenA) external pure returns (address) { //inject NONSTANDARD NAMING return UniswapV2Library.PAIRFOR87(factory868, tokenA, address(weth411)); } constructor() public { governance = msg.sender; } function UPDATEPAIR621(address pair) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING return _UPDATE639(pair); } function UPDATE182(address tokenA, address tokenB) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); return _UPDATE639(pair); } function ADD508(address tokenA, address tokenB) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "UniswapV2Oracle::add: !gov"); address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); require(!_known[pair], "known"); _known[pair] = true; _pairs.push(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); } function WORK476() public UPKEEP664 { //inject NONSTANDARD NAMING bool worked = _UPDATEALL128(); require(worked, "UniswapV2Oracle: !work"); } function WORKFORFREE492() public KEEPER983 { //inject NONSTANDARD NAMING bool worked = _UPDATEALL128(); require(worked, "UniswapV2Oracle: !work"); } function LASTOBSERVATION770(address pair) public view returns (Observation memory) { //inject NONSTANDARD NAMING return observations[pair][observations[pair].length-1]; } function _UPDATEALL128() internal returns (bool updated) { //inject NONSTANDARD NAMING for (uint i = 0; i < _pairs.length; i++) { if (_UPDATE639(_pairs[i])) { updated = true; } } } function UPDATEFOR106(uint i, uint length) external KEEPER983 returns (bool updated) { //inject NONSTANDARD NAMING for (; i < length; i++) { if (_UPDATE639(_pairs[i])) { updated = true; } } } function WORKABLE40(address pair) public view returns (bool) { //inject NONSTANDARD NAMING return (block.timestamp - LASTOBSERVATION770(pair).timestamp) > periodsize934; } function WORKABLE40() external view returns (bool) { //inject NONSTANDARD NAMING for (uint i = 0; i < _pairs.length; i++) { if (WORKABLE40(_pairs[i])) { return true; } } return false; } function _UPDATE639(address pair) internal returns (bool) { //inject NONSTANDARD NAMING // we only want to commit updates once per period (i.e. windowSize / granularity) Observation memory _point = LASTOBSERVATION770(pair); uint timeElapsed = block.timestamp - _point.timestamp; if (timeElapsed > periodsize934) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); return true; } return false; } function COMPUTEAMOUNTOUT732( //inject NONSTANDARD NAMING uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) private pure returns (uint amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.MUL709(amountIn).DECODE144805(); } function _VALID458(address pair, uint age) internal view returns (bool) { //inject NONSTANDARD NAMING return (block.timestamp - LASTOBSERVATION770(pair).timestamp) <= age; } function CURRENT334(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); require(_VALID458(pair, periodsize934.MUL709(2)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); Observation memory _observation = LASTOBSERVATION770(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); if (block.timestamp == _observation.timestamp) { _observation = observations[pair][observations[pair].length-2]; } uint timeElapsed = block.timestamp - _observation.timestamp; timeElapsed = timeElapsed == 0 ? 1 : timeElapsed; if (token0 == tokenIn) { return COMPUTEAMOUNTOUT732(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); } else { return COMPUTEAMOUNTOUT732(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } function QUOTE2(address tokenIn, uint amountIn, address tokenOut, uint granularity) external view returns (uint amountOut) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); require(_VALID458(pair, periodsize934.MUL709(granularity)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint priceAverageCumulative = 0; uint length = observations[pair].length-1; uint i = length.SUB277(granularity); uint nextIndex = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } else { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } return priceAverageCumulative.DIV758(granularity); } function PRICES199(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint length = observations[pair].length-1; uint i = length.SUB277(points); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i+1; _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function HOURLY603(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(2); uint i = _len.SUB277(points.MUL709(2)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(2)) { nextIndex = i.ADD508(2); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(2); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function DAILY468(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(48); uint i = _len.SUB277(points.MUL709(48)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(48)) { nextIndex = i.ADD508(48); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(48); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function WEEKLY904(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(336); uint i = _len.SUB277(points.MUL709(336)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(336)) { nextIndex = i.ADD508(336); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(336); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function IMPLIEDVOLATILITYHOURLY328(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(HOURLY603(tokenIn, amountIn, tokenOut, 1)); } function IMPLIEDVOLATILITYDAILY500(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(DAILY468(tokenIn, amountIn, tokenOut, 1)); } function IMPLIEDVOLATILITYWEEKLY55(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(WEEKLY904(tokenIn, amountIn, tokenOut, 1)); } function SQRT123(uint256 x) public pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = (x + 1) / 2; uint256 b = x; while (c < b) { b = c; c = (x / c + c) / 2; } return b; } function STDDEV946(uint[] memory numbers) public pure returns (uint256 sd) { //inject NONSTANDARD NAMING uint sum = 0; for(uint i = 0; i < numbers.length; i++) { sum += numbers[i]; } uint256 mean = sum / numbers.length; // Integral value; float not supported in Solidity sum = 0; uint i; for(i = 0; i < numbers.length; i++) { sum += (numbers[i] - mean) ** 2; } sd = SQRT123(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity return sd; } function BLACKSCHOLESESTIMATE503( //inject NONSTANDARD NAMING uint256 _vol, uint256 _underlying, uint256 _time ) public pure returns (uint256 estimate) { estimate = 40 * _vol * _underlying * SQRT123(_time); return estimate; } function RETBASEDBLACKSCHOLESESTIMATE765( //inject NONSTANDARD NAMING uint256[] memory _numbers, uint256 _underlying, uint256 _time ) public pure { uint _vol = STDDEV946(_numbers); BLACKSCHOLESESTIMATE503(_vol, _underlying, _time); } receive() external payable {} function _SWAP523(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING kp3r674.APPROVE763(address(uni703), _amount); address[] memory path = new address[](2); path[0] = address(kp3r674); path[1] = address(weth411); uint[] memory amounts = uni703.SWAPEXACTTOKENSFORTOKENS109(_amount, uint256(0), path, address(this), now.ADD508(1800)); weth411.WITHDRAW840(amounts[1]); return amounts[1]; } }
inject NONSTANDARD NAMING
function KPRH771() external view returns (IKeep3rV1Helper);
12,917,703
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "../game/interfaces/Interfaces.sol"; /** * @title Celestial Castle * @notice Edited from EtherOrcsOfficial/etherOrcs-contracts. */ contract CelestialCastle is Ownable, IERC721Receiver { bool public isTravelEnabled; /// @notice Celestial portal contract. PortalLike public portal; /// @notice Freaks N Guilds token contract. IFnG public freaksNGuilds; /// @notice Freaks bucks token contract. IFBX public freaksBucks; /// @notice Contract address to it's reflection. mapping(address => address) public reflection; /// @notice Original token id owner. mapping(uint256 => address) public ownerOf; /// @notice Require that the sender is the portal for bridging operations. modifier onlyPortal() { require(msg.sender == address(portal), "CelestialCastle: sender is not the portal"); _; } /// @notice Initialize the contract. function initialize( address newPortal, address newFreaksNGuilds, address newFreaksBucks, bool newIsTravelEnabled ) external onlyOwner { portal = PortalLike(newPortal); freaksNGuilds = IFnG(newFreaksNGuilds); freaksBucks = IFBX(newFreaksBucks); isTravelEnabled = newIsTravelEnabled; } /// @notice Travel tokens to L2. function travel( uint256[] calldata freakIds, uint256[] calldata celestialIds, uint256 fbxAmount ) external { require(isTravelEnabled, "CelestialCastle: travel is disabled"); bytes[] memory calls = new bytes[]( (freakIds.length > 0 ? 1 : 0) + (celestialIds.length > 0 ? 1 : 0) + (fbxAmount > 0 ? 1 : 0) ); uint256 callsIndex = 0; if (freakIds.length > 0) { Freak[] memory freaks = new Freak[](freakIds.length); for (uint256 i = 0; i < freakIds.length; i++) { require(ownerOf[freakIds[i]] == address(0), "CelestialCastle: token already staked"); require(freaksNGuilds.isFreak(freakIds[i]), "CelestialCastle: not a freak"); ownerOf[freakIds[i]] = msg.sender; freaks[i] = freaksNGuilds.getFreakAttributes(freakIds[i]); freaksNGuilds.transferFrom(msg.sender, address(this), freakIds[i]); } calls[callsIndex] = abi.encodeWithSelector( CelestialCastle.retrieveFreakIds.selector, reflection[address(freaksNGuilds)], msg.sender, freakIds, freaks ); callsIndex++; } if (celestialIds.length > 0) { Celestial[] memory celestials = new Celestial[](celestialIds.length); for (uint256 i = 0; i < celestialIds.length; i++) { require(ownerOf[celestialIds[i]] == address(0), "CelestialCastle: token already staked"); require(!freaksNGuilds.isFreak(celestialIds[i]), "CelestialCastle: not a celestial"); ownerOf[celestialIds[i]] = msg.sender; celestials[i] = freaksNGuilds.getCelestialAttributes(celestialIds[i]); freaksNGuilds.transferFrom(msg.sender, address(this), celestialIds[i]); } calls[callsIndex] = abi.encodeWithSelector( CelestialCastle.retrieveCelestialIds.selector, reflection[address(freaksNGuilds)], msg.sender, celestialIds, celestials ); callsIndex++; } if (fbxAmount > 0) { freaksBucks.burn(msg.sender, fbxAmount); calls[callsIndex] = abi.encodeWithSelector( CelestialCastle.retrieveBucks.selector, reflection[address(freaksBucks)], msg.sender, fbxAmount ); } portal.sendMessage(abi.encode(reflection[address(this)], calls)); } /// @notice Retrieve freaks from castle when bridging. function retrieveFreakIds( address fng, address owner, uint256[] calldata freakIds, Freak[] calldata freakAttributes ) external onlyPortal { for (uint256 i = 0; i < freakIds.length; i++) { delete ownerOf[freakIds[i]]; IFnG(fng).transferFrom(address(this), owner, freakIds[i]); IFnG(fng).setFreakAttributes(freakIds[i], freakAttributes[i]); } } /// @notice Retrieve celestials from castle when bridging. function retrieveCelestialIds( address fng, address owner, uint256[] calldata celestialIds, Celestial[] calldata celestialAttributes ) external onlyPortal { for (uint256 i = 0; i < celestialIds.length; i++) { delete ownerOf[celestialIds[i]]; IFnG(fng).transferFrom(address(this), owner, celestialIds[i]); IFnG(fng).setCelestialAttributes(celestialIds[i], celestialAttributes[i]); } } // function callFnG(bytes calldata data) external onlyPortal { // (bool succ, ) = freaksNGuilds.call(data) // } /// @notice Retrive freaks bucks to `owner` when bridging. function retrieveBucks( address fbx, address owner, uint256 value ) external onlyPortal { IFBX(fbx).mint(owner, value); } /// @notice Set contract reflection address on L2. function setReflection(address key, address value) external onlyOwner { reflection[key] = value; reflection[value] = key; } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external pure override returns (bytes4) { return this.onERC721Received.selector; } function setIsTravelEnabled(bool newIsTravelEnabled) external onlyOwner { isTravelEnabled = newIsTravelEnabled; } /// @notice Withdraw `amount` of ether to msg.sender. function withdraw(uint256 amount) external onlyOwner { payable(msg.sender).transfer(amount); } /// @notice Withdraw `amount` of `token` to the sender. function withdrawERC20(IERC20 token, uint256 amount) external onlyOwner { token.transfer(msg.sender, amount); } /// @notice Withdraw `tokenId` of `token` to the sender. function withdrawERC721(IERC721 token, uint256 tokenId) external onlyOwner { token.safeTransferFrom(address(this), msg.sender, tokenId); } /// @notice Withdraw `tokenId` with amount of `value` from `token` to the sender. function withdrawERC1155( IERC1155 token, uint256 tokenId, uint256 value ) external onlyOwner { token.safeTransferFrom(address(this), msg.sender, tokenId, value, ""); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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 (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @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 // 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/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: Unlicense pragma solidity 0.8.11; import "./Structs.sol"; interface MetadataHandlerLike { function getCelestialTokenURI(uint256 id, Celestial memory character) external view returns (string memory); function getFreakTokenURI(uint256 id, Freak memory character) external view returns (string memory); } interface InventoryCelestialsLike { function getAttributes(Celestial memory character, uint256 id) external pure returns (bytes memory); function getImage(uint256 id) external view returns (bytes memory); } interface InventoryFreaksLike { function getAttributes(Freak memory character, uint256 id) external view returns (bytes memory); function getImage(Freak memory character) external view returns (bytes memory); } interface IFnG { function transferFrom( address from, address to, uint256 id ) external; function ownerOf(uint256 id) external returns (address owner); function isFreak(uint256 tokenId) external view returns (bool); function getSpecies(uint256 tokenId) external view returns (uint8); function getFreakAttributes(uint256 tokenId) external view returns (Freak memory); function setFreakAttributes(uint256 tokenId, Freak memory attributes) external; function getCelestialAttributes(uint256 tokenId) external view returns (Celestial memory); function setCelestialAttributes(uint256 tokenId, Celestial memory attributes) external; } interface IFBX { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } interface ICKEY { function ownerOf(uint256 tokenId) external returns (address); } interface IVAULT { function depositsOf(address account) external view returns (uint256[] memory); function _depositedBlocks(address account, uint256 tokenId) external returns(uint256); } interface ERC20Like { function balanceOf(address from) external view returns (uint256 balance); function burn(address from, uint256 amount) external; function mint(address from, uint256 amount) external; function transfer(address to, uint256 amount) external; } interface ERC1155Like { function mint( address to, uint256 id, uint256 amount ) external; function burn( address from, uint256 id, uint256 amount ) external; } interface ERC721Like { function transferFrom( address from, address to, uint256 id ) external; function transfer(address to, uint256 id) external; function ownerOf(uint256 id) external returns (address owner); function mint(address to, uint256 tokenid) external; } interface PortalLike { function sendMessage(bytes calldata) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 pragma solidity 0.8.11; struct Freak { uint8 species; uint8 body; uint8 armor; uint8 mainHand; uint8 offHand; uint8 power; uint8 health; uint8 criticalStrikeMod; } struct Celestial { uint8 healthMod; uint8 powMod; uint8 cPP; uint8 cLevel; } struct Layer { string name; string data; } struct LayerInput { string name; string data; uint8 layerIndex; uint8 itemIndex; }
Set contract reflection address on L2.
function setReflection(address key, address value) external onlyOwner { reflection[key] = value; reflection[value] = key; }
28,797
./full_match/1/0x67360dE9BA51AB59bf0d6a4eDad27b9Bc0b05755/sources/contracts/SnarkySharks.sol
Provenance must be set and locked before sale
function setProvenanceHash(string memory provenanceHash) public onlyOwner { require(!provenanceSet,"Provenance already locked"); PROVENANCE = provenanceHash; }
17,197,223
./partial_match/1/0x67c5F13c56aEb40fd9a937214E5429dAf8A0CfC9/sources/contracts/FCNProduct.sol
Queues a withdrawal for the token holder of a specific vault token vaultAddress is the address of the vault amountShares is the number of vault tokens to be redeemed receiver is the destination user's address once funds are withdrawn/
function addToWithdrawalQueue( address vaultAddress, uint256 amountShares, address receiver ) public validVault(vaultAddress) { FCNVaultMetadata storage vaultMetadata = vaults[vaultAddress]; IERC20(vaultAddress).safeTransferFrom(receiver, address(this), amountShares); Withdrawal[] storage withdrawalQueue = withdrawalQueues[vaultAddress]; vaultMetadata.queuedWithdrawalsCount += 1; vaultMetadata.queuedWithdrawalsSharesAmount += amountShares; emit WithdrawalQueued(vaultAddress, receiver, amountShares); }
15,753,069
pragma solidity ^0.5.0; import "../libs/LibEvent.sol"; import "../libs/MerkleTreeVerifier.sol"; import "../libs/BytesArrayUtil.sol"; import "../whitelist/WhiteListUser.sol"; import "../interfaces/IEventEmitter.sol"; contract EventEmitter is WhitelistUser, IEventEmitter { using LibEvent for bytes32; using BytesArrayUtil for bytes32[]; // Events pending acknowledgement on other chains. bytes32[] public events; uint256 public chainId; event EventEmitted(bytes32 eventHash); bytes32 public nonce; // Parameters // ---------- // Event acknowledgement is at minimum 1 block after emission uint confirmationTime_blocks = 1; mapping(uint => uint) blockNumToLastEvent; uint lastEmitted_block; uint lastAcknowledged_block = block.number; uint toConfirm_block = block.number; uint lastEventEmitted_block; uint unconfirmedEventIdx; // key is a temporary parameter to ensure uniqueness // when we use a KV merkle tree, we won't need it. constructor( address _whitelist, uint256 _chainId, string memory key ) WhitelistUser(_whitelist) public { nonce = keccak256(abi.encodePacked(this, blockhash(block.number - 1), key)); chainId = _chainId; unconfirmedEventIdx = 0; lastEventEmitted_block = block.number - confirmationTime_blocks; emitEvent(nonce); } function emitEvent( bytes32 _eventDataHash ) public returns (bytes32) { // DODGY(liamz): the default is 0, which is also the same value as when there are no events. // nothing bad for now, but worth keeping in mind. // if(block.number > (lastEmitted_block + confirmationTime_blocks)) { // blockNumToLastEvent[block.number - 1] = events.length - 1; // toConfirm_block = block.number; // } // if(block.number > (lastEmitted_block + confirmationTime_blocks)) // lastEmitted_block = block.number; require(_eventDataHash != 0x00, "INVALID_EVENT_DATA"); // If this is the first tx on a new block // if(block.number > lastEventEmitted_block) { // uint confirm_block = block.number - confirmationTime_blocks; // // Update the latest block we've seen // lastEventEmitted_block = block.number; // - confirmationTime_blocks; // // Set the most recent event to ack as the most recent event we've seen // // ie. the last block we processed, emitted this event // unconfirmedEventIdx = events.length; // } // TODO implement some way of checking from which chain a event came bytes32 eventHash = LibEvent.getEventHash(_eventDataHash, msg.sender, chainId); events.push(eventHash); emit EventEmitted(eventHash); // TODO: Implement fee system return eventHash; } function getEventsCount() public view returns (uint) { return events.length; } function getLastEventToConfirm() public view returns (uint) { // We want to get the events root // but also excluding events that were emitted during this block. // #racey #justblockchainthings // // Rather than a fixed value, we parameterise this as acknowledgementDelay, // which is the index of the last event emitted in acknowledgementDelay_blocks // Events up until this block are awaiting confirmation uint confirm_block = block.number - confirmationTime_blocks; if(lastEventEmitted_block < confirm_block) { // The next update needs to acknowledge all events // Since it was so far in the past. return events.length; } else { // Else if there were events in the past `confirmationTime` blocks, // return the index of the most recent event that falls WITHIN the window return unconfirmedEventIdx; } } function getEventsRoot() public view returns(bytes32) { // if(events.length == 0) { // // return bytes32(0); // return nonce; // } return MerkleTreeVerifier._computeMerkleRoot( // events.sliceTo(getLastEventToConfirm()) events ); } function acknowledge() public { lastAcknowledged_block = block.number; unconfirmedEventIdx = events.length; } }
We want to get the events root but also excluding events that were emitted during this block. racey justblockchainthings Rather than a fixed value, we parameterise this as acknowledgementDelay, which is the index of the last event emitted in acknowledgementDelay_blocks Events up until this block are awaiting confirmation The next update needs to acknowledge all events Since it was so far in the past. Else if there were events in the past `confirmationTime` blocks, return the index of the most recent event that falls WITHIN the window
function getLastEventToConfirm() public view returns (uint) { uint confirm_block = block.number - confirmationTime_blocks; if(lastEventEmitted_block < confirm_block) { return events.length; return unconfirmedEventIdx; } }
6,346,065
pragma solidity 0.4.24; import "./PumaPayToken.sol"; /// @title TokenMultiSigWallet wallet - Allows two parties to agree on token transactions before execution. /// Only after a predefined amount of time (120 days) the super owner can transfer all the tokens to another wallet. /// This Token Multisig Wallet a modified version of the Gnosis Mutlsig Wallet - https://github.com/gnosis/MultiSigWallet /// @author Giorgos Kourtellos - <[email protected]> contract TokenMultiSigWallet { /// ================================================================================================================= /// Events /// ================================================================================================================= event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); /// ================================================================================================================= /// Constants /// ================================================================================================================= uint constant public REQUIRED_SIGNATURES = 2; uint constant public OPTION_TIME_FRAME = 120 days; /// ================================================================================================================= /// Members /// ================================================================================================================= mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public transactionCount; uint256 public optionStartTime; PumaPayToken public token; address public superOwner; struct Transaction { address destination; uint value; bool executed; } /// ================================================================================================================= /// Modifiers /// ================================================================================================================= modifier isSuperOwner() { require(msg.sender == superOwner); _; } modifier afterOptionTimeFramePassed() { require(optionStartTime + OPTION_TIME_FRAME < now); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validValue(uint _value) { require(_value <= token.balanceOf(this)); _; } modifier validRequirement(address _superOwner, address _normalOwner, PumaPayToken _token) { require( _superOwner != address(0) && _normalOwner != address(0) && _superOwner != _normalOwner && _token != address(0) ); _; } /// ================================================================================================================= /// Constructor /// ================================================================================================================= /// @dev Contract constructor sets the super owner and normal onwer and the token that will be held in the wallet. /// @param _superOwner Super Owner. /// @param _normalOwner Normal Owner. /// @param _token Token Address. constructor(address _superOwner, address _normalOwner, PumaPayToken _token) public validRequirement(_superOwner, _normalOwner, _token) { owners.push(_superOwner); owners.push(_normalOwner); for (uint i = 0; i < owners.length; i++) { isOwner[owners[i]] = true; } superOwner = _superOwner; token = _token; optionStartTime = now; transactionCount = 1; } // ================================================================================================================= // Public Functions // ================================================================================================================= /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @return Returns transaction ID. function submitTransaction(address destination, uint value) public returns (uint transactionId) { transactionId = addTransaction(destination, value); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == REQUIRED_SIGNATURES) return true; } } function claimAllTokensAfterTimeLock(address ethWallet) public isSuperOwner() afterOptionTimeFramePassed() notNull(ethWallet) { token.transfer(ethWallet, token.balanceOf(this)); } // ================================================================================================================= // Internal Functions // ================================================================================================================= /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @return Returns transaction ID. function addTransaction(address destination, uint value) internal notNull(destination) validValue(value) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, executed: false }); transactionCount += 1; emit Submission(transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) internal ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) validValue(transactions[transactionId].value) { if (isConfirmed(transactionId)) { token.transfer(transactions[transactionId].destination, transactions[transactionId].value); transactions[transactionId].executed = true; emit Execution(transactionId); } } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { count += 1; } } } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i = 0; i < transactionCount - 1; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { count += 1; } } } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { require(to > from); uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 1; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } } }
Returns total number of transactions after filers are applied. pending Include pending transactions. executed Include executed transactions. return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i = 0; i < transactionCount - 1; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { count += 1; } } }
14,017,003
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IPAYR.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract PAYR is Ownable, IPAYR { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private _maxSupply = 200000000 * (10 ** 18); string private _name="PayrLink"; string private _symbol="PAYR"; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor () { } /** * @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 this function is * overloaded; * * 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 pure returns (uint8) { return 18; } /** * @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 override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view 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 override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * 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 override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, msg.sender, 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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(msg.sender, spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function mint(address account, uint256 amount) public onlyOwner { require(account != address(0), "ERC20: mint to the zero address"); require(_maxSupply > _totalSupply, "Minting is Finished."); uint256 _amount = _maxSupply - _totalSupply; if (_amount > amount) { _amount = amount; } _totalSupply += _amount; _balances[account] += _amount; emit Transfer(address(0), account, _amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function burn(address account, uint256 amount) public onlyOwner { require(account != address(0), "ERC20: burn from the zero address"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { 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); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IPAYR { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`./
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(msg.sender, spender, currentAllowance - subtractedValue); return true; }
6,260,215
// SPDX-License-Identifier: Apache-2.0 // Copyright 2020 [email protected] // contracts/interfaces/ISwapPetOracle.sol pragma solidity ^0.7.0; /// @title Interface for interacting with price Oracle of Swap.Pet. /// @author [email protected] /// @dev price on base/quote, swaper for exchange between base and quote. interface ISwapPetOracle { /// @notice the price(scaled by 1e18) of base_/quote_. // / @returns return 0 if false or not support the base_/quote_. function price(address base_,address quote_) external view returns (uint256); /// @notice swap Check amountIn_ tokenIn_ to amountOut_ tokenOut_. // / @returns 0 with do nothing or do not support base_/quote_ swap. function swap(address tokenIn_,address tokenOut_,uint256 amountIn_) external returns (uint256 amountOut_); }
Interface for interacting with price Oracle of Swap.Pet. [email protected] price on base/quote, swaper for exchange between base and quote. / returns return 0 if false or not support the base_/quote_. / returns 0 with do nothing or do not support base_/quote_ swap.
interface ISwapPetOracle { function price(address base_,address quote_) external view returns (uint256); function swap(address tokenIn_,address tokenOut_,uint256 amountIn_) external returns (uint256 amountOut_); pragma solidity ^0.7.0; }
6,435,160
pragma solidity ^0.4.24; contract CryptoFiat { address public masterAccount; modifier onlyMasterAccount { require(msg.sender == masterAccount); _ ; } // lookup table for finding a particular contract by ID mapping(uint256 => address) public contractAddress; mapping(address => uint256) public contractId; function contractActive(address addr) public view returns (bool) { return contractId[addr] > 0; } // list of contracts involved in this CryptoFiat instance // use this list of contracts for filtering for events address[] public contracts; function contractsLength() public view returns (uint256) { return contracts.length; } constructor() public { masterAccount = msg.sender; contracts.push(address(this)); } function appointMasterAccount(address next) public onlyMasterAccount { masterAccount = next; } event ContractUpgraded(uint256 indexed id, address previous, address next); function upgrade(uint256 id, address next) public { require(id != 0); address prev = contractAddress[id]; require(prev != next); // message sender or the previous contract bool canUpgrade = (msg.sender == masterAccount) || (msg.sender == prev); require(canUpgrade); // check double use of contract require(!contractActive(next)); // disable previous contract contractId[prev] = 0; // activate next contract contractAddress[id] = next; if (next != 0x0000000000000000000000000000000000000000) contractId[next] = id; // finalize emit ContractUpgraded(id, prev, next); contracts.push(next); } } contract Data { CryptoFiat public cryptoFiat; constructor(CryptoFiat _cryptoFiat) public { cryptoFiat = _cryptoFiat; } modifier onlyContracts { require(cryptoFiat.contractActive(msg.sender)); _; } mapping(bytes32 => bytes32) private _data; function set(uint256 bucket, bytes32 key, bytes32 value) public onlyContracts { _data[keccak256(abi.encodePacked(bucket, key))] = value; } function get(uint256 bucket, bytes32 key) public view returns (bytes32) { return _data[keccak256(abi.encodePacked(bucket, key))]; } } contract Constants { address constant WORLD = 0x0000000000000000000000000000000000000000; // contract id uint256 constant DATA = 1; uint256 constant ACCOUNTS = 2; uint256 constant APPROVING = 3; uint256 constant RESERVE = 4; uint256 constant ENFORCEMENT = 5; uint256 constant ACCOUNT_RECOVERY = 6; uint256 constant DELEGATION = 7; // bucket identifiers uint256 constant STATUS = 1; uint256 constant BALANCE = 2; uint256 constant DELEGATED_TRANSFER_NONCE = 3; uint256 constant RECOVERY_ACCOUNT = 4; uint256 constant TOTAL_SUPPLY = 5; // account states uint256 constant APPROVED = 1; uint256 constant CLOSED = 2; uint256 constant FROZEN = 4; // events event Transfer(address indexed source, address indexed destination, uint256 amount); event AccountApproved(address indexed source); event AccountClosed(address indexed source); event AccountFreeze(address indexed source, bool frozen); event SupplyChanged(uint256 totalSupply); } contract InternalData is Constants { CryptoFiat public cryptoFiat; Data public data; modifier onlyMasterAccount { require(cryptoFiat.masterAccount() == msg.sender); _; } function switchCryptoFiat(CryptoFiat next) public onlyMasterAccount { cryptoFiat = next; } function switchData(Data next) public onlyMasterAccount { data = next; } function cacheData() internal { data = Data(contractAddress(DATA)); require(address(data) != WORLD); } function contractAddress(uint256 id) internal view returns (address) { return cryptoFiat.contractAddress(id); } function accounts() internal view returns (Accounts) { return Accounts(contractAddress(ACCOUNTS)); } function approving() internal view returns (Approving) { return Approving(contractAddress(APPROVING)); } function reserve() internal view returns (Reserve) { return Reserve(contractAddress(RESERVE)); } function enforcement() internal view returns (Enforcement) { return Enforcement(contractAddress(ENFORCEMENT)); } function accountRecovery() internal view returns (AccountRecovery) { return AccountRecovery(contractAddress(ACCOUNT_RECOVERY)); } function delegation() internal view returns (Delegation) { return Delegation(contractAddress(DELEGATION)); } // balance contains the balance of an account function _balanceOf(address addr) internal view returns (uint256) { return uint256(data.get(BALANCE, bytes20(addr))); } function _setBalanceOf(address addr, uint256 value) internal { data.set(BALANCE, bytes20(addr), bytes32(value)); } // state contains the current state of an account function _statusOf(address addr) internal view returns (uint256) { return uint256(data.get(STATUS, bytes20(addr))); } function _setStatusOf(address addr, uint256 value) internal { data.set(STATUS, bytes20(addr), bytes32(value)); } // delegated trancfer nonce contains the last nonce used in delegatedTransfer function _delegatedTransferNonceOf(address addr) internal view returns (uint256) { return uint256(data.get(DELEGATED_TRANSFER_NONCE, bytes20(addr))); } function _setDelegatedTransferNonceOf(address addr, uint256 value) internal { data.set(DELEGATED_TRANSFER_NONCE, bytes20(addr), bytes32(value)); } // recovery account contains a fallback account that can be used to recover funds function _recoveryAccountOf(address addr) internal view returns (address) { return address(bytes20(data.get(RECOVERY_ACCOUNT, bytes20(addr)))); } function _setRecoveryAccountOf(address addr, address value) internal { data.set(RECOVERY_ACCOUNT, bytes20(addr), bytes20(value)); } // totalSupply is the total amount of tokens in circulation function _totalSupply() internal view returns (uint256) { return uint256(data.get(TOTAL_SUPPLY, bytes32(0))); } function _setTotalSupply(uint256 value) internal { data.set(TOTAL_SUPPLY, bytes32(0), bytes32(value)); } // for checking account status function _isApproved(address account) internal view returns (bool) { return _statusOf(account) & APPROVED == APPROVED; } function _isClosed(address account) internal view returns (bool) { return _statusOf(account) & CLOSED == CLOSED; } function _isFrozen(address account) internal view returns (bool) { return _statusOf(account) & FROZEN == FROZEN; } modifier canSend(address account) { uint256 status = _statusOf(account); require(status & APPROVED == APPROVED); require(status & FROZEN != FROZEN); require(account != WORLD); _; } function assertSend(address account) internal view canSend(account) {} modifier canReceive(address account) { require(!_isClosed(account)); require(account != WORLD); _; } function assertReceive(address account) internal view canReceive(account) {} // internal modification of balance function _withdraw(address account, uint256 amount) internal { // check for underflow uint256 balance = _balanceOf(account); require(balance >= amount); _setBalanceOf(account, balance - amount); } function _deposit(address account, uint256 amount) internal { // check for overflow uint256 balance = _balanceOf(account); require(balance + amount >= balance); _setBalanceOf(account, balance + amount); } } contract Accounts is InternalData { constructor(CryptoFiat _cryptoFiat) public { cryptoFiat = _cryptoFiat; cacheData(); } // balance contains the balance of an account function balanceOf(address addr) public view returns (uint256) { return _balanceOf(addr); } function statusOf(address addr) public view returns (uint256) { return _statusOf(addr); } function isApproved(address account) public view returns (bool) { return _isApproved(account); } function isClosed(address account) public view returns (bool) { return _isClosed(account); } function isFrozen(address account) public view returns (bool) { return _isFrozen(account); } function transfer(address destination, uint256 amount) public canSend(msg.sender) canReceive(destination) { address source = msg.sender; _withdraw(source, amount); _deposit(destination, amount); emit Transfer(source, destination, amount); } } contract Approving is InternalData { address public accountApprover; constructor(CryptoFiat _cryptoFiat, address _accountApprover) public { cryptoFiat = _cryptoFiat; cacheData(); accountApprover = _accountApprover; } modifier onlyAccountApprover { require(msg.sender == accountApprover); _; } function appointAccountApprover(address next) public onlyAccountApprover { accountApprover = next; } // approveAccount makes it possible for an account to send money function approveAccount(address account) public onlyAccountApprover { _setStatusOf(account, _statusOf(account) | APPROVED); emit AccountApproved(account); } // approveAccounts approves multiple accounts function approveAccounts(address[] accounts) public { for (uint i = 0; i < accounts.length; i += 1) { approveAccount(accounts[i]); } } // closeAccount closes the account for receiving money function closeAccount(address account) public onlyAccountApprover { _setStatusOf(account, _statusOf(account) | CLOSED); emit AccountClosed(account); } } contract Reserve is InternalData { address public reserveBank; constructor(CryptoFiat _cryptoFiat, address _reserveBank) public { cryptoFiat = _cryptoFiat; cacheData(); reserveBank = _reserveBank; } modifier onlyReserveBank { require(msg.sender == reserveBank); _; } function appointReserveBank(address next) public onlyReserveBank { reserveBank = next; } function totalSupply() public view returns (uint256) { return _totalSupply(); } // increaseSupply increases the tokens in circulation function increaseSupply(uint256 amount) public onlyReserveBank canReceive(reserveBank) { uint256 supply = totalSupply(); require(supply + amount >= supply); supply += amount; _setTotalSupply(supply); _deposit(reserveBank, amount); emit Transfer(WORLD, reserveBank, amount); emit SupplyChanged(supply); } // decreaseSupply decreases the amount of tokens in circulation function decreaseSupply(uint256 amount) public onlyReserveBank canSend(reserveBank) { uint256 supply = _totalSupply(); require(supply >= amount); supply -= amount; _setTotalSupply(supply); _withdraw(reserveBank, amount); emit Transfer(reserveBank, WORLD, amount); emit SupplyChanged(supply); } } contract Enforcement is InternalData { address public lawEnforcer; address public accountDesignator; address public account; constructor(CryptoFiat _cryptoFiat, address _lawEnforcer, address _enforcementAccountDesignator, address _enforcementAccount) public { cryptoFiat = _cryptoFiat; cacheData(); lawEnforcer = _lawEnforcer; accountDesignator = _enforcementAccountDesignator; account = _enforcementAccount; } modifier onlyLawEnforcer { require(msg.sender == lawEnforcer); _; } modifier onlyAccountDesignator { require(msg.sender == accountDesignator); _; } function appointLawEnforcer(address next) public onlyLawEnforcer { lawEnforcer = next; } function appointAccountDesignator(address next) public onlyAccountDesignator { accountDesignator = next; } // withdraw allows law enforcerer to withdraw to a dedicated account function withdraw(address from, uint256 amount) public onlyLawEnforcer canReceive(account) { _withdraw(from, amount); _deposit(account, amount); emit Transfer(from, account, amount); } // freezeAccount disallows account to send money function freezeAccount(address target) public onlyLawEnforcer { _setStatusOf(target, _statusOf(target) | FROZEN); emit AccountFreeze(target, true); } // unfreezeAccount re-allows account to send money function unfreezeAccount(address target) public onlyLawEnforcer { _setStatusOf(target, _statusOf(target) & ~FROZEN); emit AccountFreeze(target, false); } // designateAccount allows changing the account function designateAccount(address _account) public onlyAccountDesignator canReceive(_account) { account = _account; } } contract AccountRecovery is InternalData { constructor(CryptoFiat _cryptoFiat) public { cryptoFiat = _cryptoFiat; cacheData(); } // designateRecoveryAccount allows msg.sender to specify a trusted account // that can recover the tokens function designateRecoveryAccount(address recoveryAccount) public { _setRecoveryAccountOf(msg.sender, recoveryAccount); } // recoverBalance allows to recover tokens on a particular account // recovering a balance will automatically close the account function recoverBalance(address from, address into) public canSend(from) canReceive(into) { require(msg.sender == _recoveryAccountOf(from)); // close the account _setStatusOf(from, _statusOf(from) | CLOSED); emit AccountClosed(from); uint256 amount = _balanceOf(from); _withdraw(from, amount); _deposit(into, amount); emit Transfer(from, into, amount); } } contract Delegation is InternalData { constructor(CryptoFiat _cryptoFiat) public { cryptoFiat = _cryptoFiat; cacheData(); } function nonceOf(address account) public view returns (uint256) { return _delegatedTransferNonceOf(account); } function recoverSigner(bytes32 hash, bytes signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; require(signature.length == 65); assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := and(mload(add(signature, 65)), 255) } if (v < 27) { v += 27; } return ecrecover(hash, v, r, s); } function transfer( // transfer request uint256 nonce, address destination, uint256 amount, uint256 fee, // transfer request signed by source bytes signature, // whom to pay for fulfilling transfer address delegate ) public canReceive(destination) canReceive(delegate) { // extract source from signature address source = recoverSigner( keccak256(abi.encodePacked(nonce, destination, amount, fee)), signature ); // check whether source can send assertSend(source); // protect against replayed transactions require(_delegatedTransferNonceOf(source) < nonce); _setDelegatedTransferNonceOf(source, nonce); _withdraw(source, amount + fee); _deposit(destination, amount); emit Transfer(source, destination, amount); if (fee > 0) { _deposit(delegate, fee); emit Transfer(source, delegate, fee); } } uint constant XFER_SIZE = 32+20+32+32+(32+32+1); // expected format // struct XferEncoded { // uint256 nonce; // 32 = 32 // address destination; // 20 = 52 // uint256 amount; // 32 = 84 // uint256 fee; // 32 = 116 // bytes32 r; // 32 = 148 // bytes32 s; // 32 = 180 // uint8 v; // 1 = 181 // } struct Xfer { uint256 nonce; address source; address destination; uint256 amount; uint256 fee; } function recoverXfer(bytes data, uint offset) internal pure returns (Xfer) { uint base = XFER_SIZE * offset; uint256 nonce; address destination; uint256 amount; uint256 fee; bytes32 r; bytes32 s; uint8 v; assembly { data := add(data, base) nonce := mload(add(data, 32)) destination := mload(add(data, 52)) amount := mload(add(data, 84)) fee := mload(add(data, 116)) r := mload(add(data, 148)) s := mload(add(data, 180)) v := and(mload(add(data, 181)), 255) } if (v < 27) { v += 27; } bytes32 hash = keccak256(abi.encodePacked(nonce, destination, amount, fee)); Xfer memory xfer; xfer.nonce = nonce; xfer.source = ecrecover(hash, v, r, s); xfer.destination = destination; xfer.amount = amount; xfer.fee = fee; return xfer; } function multitransfer( uint256 count, bytes transfers, address delegate ) public canReceive(delegate) { for (uint i = 0; i < count; i++) { Xfer memory xfer = recoverXfer(transfers, i); // check whether source can send assertSend(xfer.source); assertReceive(xfer.destination); // protect against replayed transactions require(_delegatedTransferNonceOf(xfer.source) < xfer.nonce); _setDelegatedTransferNonceOf(xfer.source, xfer.nonce); _withdraw(xfer.source, xfer.amount + xfer.fee); _deposit(xfer.destination, xfer.amount); emit Transfer(xfer.source, xfer.destination, xfer.amount); if (xfer.fee > 0) { _deposit(delegate, xfer.fee); emit Transfer(xfer.source, delegate, xfer.fee); } } } }
for checking account status
function _isApproved(address account) internal view returns (bool) { return _statusOf(account) & APPROVED == APPROVED; }
5,384,904
pragma solidity ^0.5.5; library strings { struct slice { uint _len; uint _ptr; } function MEMCPY184(uint dest, uint src, uint len) private pure { //inject NONSTANDARD NAMING // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function TOSLICE667(string memory self) internal pure returns (slice memory) { //inject NONSTANDARD NAMING uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } function LEN420(bytes32 self) internal pure returns (uint) { //inject NONSTANDARD NAMING uint ret; if (self == 0) return 0; if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (uint(self) & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (uint(self) & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (uint(self) & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (uint(self) & 0xff == 0) { ret += 1; } return 32 - ret; } function TOSLICEB32242(bytes32 self) internal pure returns (slice memory ret) { //inject NONSTANDARD NAMING // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = LEN420(self); } function COPY737(slice memory self) internal pure returns (slice memory) { //inject NONSTANDARD NAMING return slice(self._len, self._ptr); } function TOSTRING824(slice memory self) internal pure returns (string memory) { //inject NONSTANDARD NAMING string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } MEMCPY184(retptr, self._ptr, self._len); return ret; } function LEN420(slice memory self) internal pure returns (uint l) { //inject NONSTANDARD NAMING // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } function EMPTY246(slice memory self) internal pure returns (bool) { //inject NONSTANDARD NAMING return self._len == 0; } function COMPARE76(slice memory self, slice memory other) internal pure returns (int) { //inject NONSTANDARD NAMING uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } function EQUALS848(slice memory self, slice memory other) internal pure returns (bool) { //inject NONSTANDARD NAMING return COMPARE76(self, other) == 0; } function NEXTRUNE884(slice memory self, slice memory rune) internal pure returns (slice memory) { //inject NONSTANDARD NAMING rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } function NEXTRUNE884(slice memory self) internal pure returns (slice memory ret) { //inject NONSTANDARD NAMING NEXTRUNE884(self, ret); } function ORD412(slice memory self) internal pure returns (uint ret) { //inject NONSTANDARD NAMING if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } function KECCAK7(slice memory self) internal pure returns (bytes32 ret) { //inject NONSTANDARD NAMING assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } function STARTSWITH158(slice memory self, slice memory needle) internal pure returns (bool) { //inject NONSTANDARD NAMING if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } function BEYOND684(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } function ENDSWITH884(slice memory self, slice memory needle) internal pure returns (bool) { //inject NONSTANDARD NAMING if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } function UNTIL972(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function FINDPTR600(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { //inject NONSTANDARD NAMING uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function RFINDPTR373(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { //inject NONSTANDARD NAMING uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } function FIND686(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING uint ptr = FINDPTR600(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } function RFIND966(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING uint ptr = RFINDPTR373(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } function SPLIT752(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { //inject NONSTANDARD NAMING uint ptr = FINDPTR600(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } function SPLIT752(slice memory self, slice memory needle) internal pure returns (slice memory token) { //inject NONSTANDARD NAMING SPLIT752(self, needle, token); } function RSPLIT98(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { //inject NONSTANDARD NAMING uint ptr = RFINDPTR373(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } function RSPLIT98(slice memory self, slice memory needle) internal pure returns (slice memory token) { //inject NONSTANDARD NAMING RSPLIT98(self, needle, token); } function COUNT317(slice memory self, slice memory needle) internal pure returns (uint cnt) { //inject NONSTANDARD NAMING uint ptr = FINDPTR600(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = FINDPTR600(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } function CONTAINS145(slice memory self, slice memory needle) internal pure returns (bool) { //inject NONSTANDARD NAMING return RFINDPTR373(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } function CONCAT154(slice memory self, slice memory other) internal pure returns (string memory) { //inject NONSTANDARD NAMING string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } MEMCPY184(retptr, self._ptr, self._len); MEMCPY184(retptr + self._len, other._ptr, other._len); return ret; } function JOIN989(slice memory self, slice[] memory parts) internal pure returns (string memory) { //inject NONSTANDARD NAMING if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(uint i = 0; i < parts.length; i++) { MEMCPY184(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { MEMCPY184(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } interface IERC165 { function SUPPORTSINTERFACE706(bytes4 interfaceId) external view returns (bool); //inject NONSTANDARD NAMING } contract IERC721 is IERC165 { event TRANSFER150(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVAL578(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVALFORALL29(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING function BALANCEOF194(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING function OWNEROF501(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING function SAFETRANSFERFROM763(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function TRANSFERFROM196(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function APPROVE594(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function GETAPPROVED68(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING function SETAPPROVALFORALL944(address operator, bool _approved) public; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL189(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING function SAFETRANSFERFROM763(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING } contract IERC721Metadata is IERC721 { function NAME560() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL235() external view returns (string memory); //inject NONSTANDARD NAMING function TOKENURI443(uint256 tokenId) external view returns (string memory); //inject NONSTANDARD NAMING } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER492() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA8() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract IERC721Enumerable is IERC721 { function TOTALSUPPLY60() public view returns (uint256); //inject NONSTANDARD NAMING function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256 tokenId); //inject NONSTANDARD NAMING function TOKENBYINDEX294(uint256 index) public view returns (uint256); //inject NONSTANDARD NAMING } contract IERC721Receiver { function ONERC721RECEIVED434(address operator, address from, uint256 tokenId, bytes memory data) //inject NONSTANDARD NAMING public returns (bytes4); } library SafeMath { function ADD556(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB290(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB290(a, b, "SafeMath: subtraction overflow"); } function SUB290(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL948(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV752(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV752(a, b, "SafeMath: division by zero"); } function DIV752(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD555(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD555(a, b, "SafeMath: modulo by zero"); } function MOD555(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT48(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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. // 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 != 0x0 && codehash != accountHash); } function TOPAYABLE256(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } } library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function CURRENT546(Counter storage counter) internal view returns (uint256) { //inject NONSTANDARD NAMING return counter._value; } function INCREMENT933(Counter storage counter) internal { //inject NONSTANDARD NAMING // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function DECREMENT749(Counter storage counter) internal { //inject NONSTANDARD NAMING counter._value = counter._value.SUB290(1); } } contract ERC165 is IERC165 { bytes4 private constant _interface_id_erc165217 = 0x01ffc9a7; //inject NONSTANDARD NAMING mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _REGISTERINTERFACE617(_interface_id_erc165217); } function SUPPORTSINTERFACE706(bytes4 interfaceId) external view returns (bool) { //inject NONSTANDARD NAMING return _supportedInterfaces[interfaceId]; } function _REGISTERINTERFACE617(bytes4 interfaceId) internal { //inject NONSTANDARD NAMING require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _erc721_received995 = 0x150b7a02; //inject NONSTANDARD NAMING // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _interface_id_erc721781 = 0x80ac58cd; //inject NONSTANDARD NAMING constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _REGISTERINTERFACE617(_interface_id_erc721781); } function BALANCEOF194(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].CURRENT546(); } function OWNEROF501(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function APPROVE594(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING address owner = OWNEROF501(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_MSGSENDER492() == owner || ISAPPROVEDFORALL189(owner, _MSGSENDER492()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit APPROVAL578(owner, to, tokenId); } function GETAPPROVED68(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING require(_EXISTS310(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function SETAPPROVALFORALL944(address to, bool approved) public { //inject NONSTANDARD NAMING require(to != _MSGSENDER492(), "ERC721: approve to caller"); _operatorApprovals[_MSGSENDER492()][to] = approved; emit APPROVALFORALL29(_MSGSENDER492(), to, approved); } function ISAPPROVEDFORALL189(address owner, address operator) public view returns (bool) { //inject NONSTANDARD NAMING return _operatorApprovals[owner][operator]; } function TRANSFERFROM196(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING //solhint-disable-next-line max-line-length require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved"); _TRANSFERFROM267(from, to, tokenId); } function SAFETRANSFERFROM763(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING SAFETRANSFERFROM763(from, to, tokenId, ""); } function SAFETRANSFERFROM763(address from, address to, uint256 tokenId, bytes memory _data) public { //inject NONSTANDARD NAMING require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved"); _SAFETRANSFERFROM629(from, to, tokenId, _data); } function _SAFETRANSFERFROM629(address from, address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING _TRANSFERFROM267(from, to, tokenId); require(_CHECKONERC721RECEIVED542(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _EXISTS310(uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING address owner = _tokenOwner[tokenId]; return owner != address(0); } function _ISAPPROVEDOROWNER717(address spender, uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING require(_EXISTS310(tokenId), "ERC721: operator query for nonexistent token"); address owner = OWNEROF501(tokenId); return (spender == owner || GETAPPROVED68(tokenId) == spender || ISAPPROVEDFORALL189(owner, spender)); } function _SAFEMINT616(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING _SAFEMINT616(to, tokenId, ""); } function _SAFEMINT616(address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING _MINT975(to, tokenId); require(_CHECKONERC721RECEIVED542(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _MINT975(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(to != address(0), "ERC721: mint to the zero address"); require(!_EXISTS310(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].INCREMENT933(); emit TRANSFER150(address(0), to, tokenId); } function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(OWNEROF501(tokenId) == owner, "ERC721: burn of token that is not own"); _CLEARAPPROVAL18(tokenId); _ownedTokensCount[owner].DECREMENT749(); _tokenOwner[tokenId] = address(0); emit TRANSFER150(owner, address(0), tokenId); } function _BURN381(uint256 tokenId) internal { //inject NONSTANDARD NAMING _BURN381(OWNEROF501(tokenId), tokenId); } function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(OWNEROF501(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _CLEARAPPROVAL18(tokenId); _ownedTokensCount[from].DECREMENT749(); _ownedTokensCount[to].INCREMENT933(); _tokenOwner[tokenId] = to; emit TRANSFER150(from, to, tokenId); } function _CHECKONERC721RECEIVED542(address from, address to, uint256 tokenId, bytes memory _data) //inject NONSTANDARD NAMING internal returns (bool) { if (!to.ISCONTRACT48()) { return true; } bytes4 retval = IERC721Receiver(to).ONERC721RECEIVED434(_MSGSENDER492(), from, tokenId, _data); return (retval == _erc721_received995); } function _CLEARAPPROVAL18(uint256 tokenId) private { //inject NONSTANDARD NAMING if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; bytes4 private constant _interface_id_erc721_enumerable707 = 0x780e9d63; //inject NONSTANDARD NAMING constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _REGISTERINTERFACE617(_interface_id_erc721_enumerable707); } function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING require(index < BALANCEOF194(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } function TOTALSUPPLY60() public view returns (uint256) { //inject NONSTANDARD NAMING return _allTokens.length; } function TOKENBYINDEX294(uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING require(index < TOTALSUPPLY60(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._TRANSFERFROM267(from, to, tokenId); _REMOVETOKENFROMOWNERENUMERATION42(from, tokenId); _ADDTOKENTOOWNERENUMERATION485(to, tokenId); } function _MINT975(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._MINT975(to, tokenId); _ADDTOKENTOOWNERENUMERATION485(to, tokenId); _ADDTOKENTOALLTOKENSENUMERATION66(tokenId); } function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._BURN381(owner, tokenId); _REMOVETOKENFROMOWNERENUMERATION42(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _REMOVETOKENFROMALLTOKENSENUMERATION970(tokenId); } function _TOKENSOFOWNER469(address owner) internal view returns (uint256[] storage) { //inject NONSTANDARD NAMING return _ownedTokens[owner]; } function _ADDTOKENTOOWNERENUMERATION485(address to, uint256 tokenId) private { //inject NONSTANDARD NAMING _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } function _ADDTOKENTOALLTOKENSENUMERATION66(uint256 tokenId) private { //inject NONSTANDARD NAMING _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _REMOVETOKENFROMOWNERENUMERATION42(address from, uint256 tokenId) private { //inject NONSTANDARD NAMING // 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 = _ownedTokens[from].length.SUB290(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 _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } function _REMOVETOKENFROMALLTOKENSENUMERATION970(uint256 tokenId) private { //inject NONSTANDARD NAMING // 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.SUB290(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 _allTokens.length--; _allTokensIndex[tokenId] = 0; } } contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED55(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER492(); _owner = msgSender; emit OWNERSHIPTRANSFERRED55(address(0), msgSender); } function OWNER824() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER845() { //inject NONSTANDARD NAMING require(ISOWNER804(), "Ownable: caller is not the owner"); _; } function ISOWNER804() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER492() == _owner; } function RENOUNCEOWNERSHIP585() public ONLYOWNER845 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED55(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP274(address newOwner) public ONLYOWNER845 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP356(newOwner); } function _TRANSFEROWNERSHIP356(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED55(_owner, newOwner); _owner = newOwner; } } contract NoMintERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _erc721_received995 = 0x150b7a02; //inject NONSTANDARD NAMING // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _interface_id_erc721781 = 0x80ac58cd; //inject NONSTANDARD NAMING constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _REGISTERINTERFACE617(_interface_id_erc721781); } function BALANCEOF194(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].CURRENT546(); } function OWNEROF501(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function APPROVE594(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING address owner = OWNEROF501(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_MSGSENDER492() == owner || ISAPPROVEDFORALL189(owner, _MSGSENDER492()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit APPROVAL578(owner, to, tokenId); } function GETAPPROVED68(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING require(_EXISTS310(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function SETAPPROVALFORALL944(address to, bool approved) public { //inject NONSTANDARD NAMING require(to != _MSGSENDER492(), "ERC721: approve to caller"); _operatorApprovals[_MSGSENDER492()][to] = approved; emit APPROVALFORALL29(_MSGSENDER492(), to, approved); } function ISAPPROVEDFORALL189(address owner, address operator) public view returns (bool) { //inject NONSTANDARD NAMING return _operatorApprovals[owner][operator]; } function TRANSFERFROM196(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING //solhint-disable-next-line max-line-length require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved"); _TRANSFERFROM267(from, to, tokenId); } function SAFETRANSFERFROM763(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING SAFETRANSFERFROM763(from, to, tokenId, ""); } function SAFETRANSFERFROM763(address from, address to, uint256 tokenId, bytes memory _data) public { //inject NONSTANDARD NAMING require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved"); _SAFETRANSFERFROM629(from, to, tokenId, _data); } function _SAFETRANSFERFROM629(address from, address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING _TRANSFERFROM267(from, to, tokenId); require(_CHECKONERC721RECEIVED542(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _EXISTS310(uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING address owner = _tokenOwner[tokenId]; return owner != address(0); } function _ISAPPROVEDOROWNER717(address spender, uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING require(_EXISTS310(tokenId), "ERC721: operator query for nonexistent token"); address owner = OWNEROF501(tokenId); return (spender == owner || GETAPPROVED68(tokenId) == spender || ISAPPROVEDFORALL189(owner, spender)); } function _ADDTOKENTO735(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(to != address(0), "ERC721: mint to the zero address"); require(!_EXISTS310(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].INCREMENT933(); } function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(OWNEROF501(tokenId) == owner, "ERC721: burn of token that is not own"); _CLEARAPPROVAL18(tokenId); _ownedTokensCount[owner].DECREMENT749(); _tokenOwner[tokenId] = address(0); emit TRANSFER150(owner, address(0), tokenId); } function _BURN381(uint256 tokenId) internal { //inject NONSTANDARD NAMING _BURN381(OWNEROF501(tokenId), tokenId); } function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(OWNEROF501(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _CLEARAPPROVAL18(tokenId); _ownedTokensCount[from].DECREMENT749(); _ownedTokensCount[to].INCREMENT933(); _tokenOwner[tokenId] = to; emit TRANSFER150(from, to, tokenId); } function _CHECKONERC721RECEIVED542(address from, address to, uint256 tokenId, bytes memory _data) //inject NONSTANDARD NAMING internal returns (bool) { if (!to.ISCONTRACT48()) { return true; } bytes4 retval = IERC721Receiver(to).ONERC721RECEIVED434(_MSGSENDER492(), from, tokenId, _data); return (retval == _erc721_received995); } function _CLEARAPPROVAL18(uint256 tokenId) private { //inject NONSTANDARD NAMING if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } contract NoMintERC721Enumerable is Context, ERC165, NoMintERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; bytes4 private constant _interface_id_erc721_enumerable707 = 0x780e9d63; //inject NONSTANDARD NAMING constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _REGISTERINTERFACE617(_interface_id_erc721_enumerable707); } function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING require(index < BALANCEOF194(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } function TOTALSUPPLY60() public view returns (uint256) { //inject NONSTANDARD NAMING return _allTokens.length; } function TOKENBYINDEX294(uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING require(index < TOTALSUPPLY60(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._TRANSFERFROM267(from, to, tokenId); _REMOVETOKENFROMOWNERENUMERATION42(from, tokenId); _ADDTOKENTOOWNERENUMERATION485(to, tokenId); } function _ADDTOKENTO735(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._ADDTOKENTO735(to, tokenId); _ADDTOKENTOOWNERENUMERATION485(to, tokenId); _ADDTOKENTOALLTOKENSENUMERATION66(tokenId); } function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._BURN381(owner, tokenId); _REMOVETOKENFROMOWNERENUMERATION42(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _REMOVETOKENFROMALLTOKENSENUMERATION970(tokenId); } function _TOKENSOFOWNER469(address owner) internal view returns (uint256[] storage) { //inject NONSTANDARD NAMING return _ownedTokens[owner]; } function _ADDTOKENTOOWNERENUMERATION485(address to, uint256 tokenId) private { //inject NONSTANDARD NAMING _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } function _ADDTOKENTOALLTOKENSENUMERATION66(uint256 tokenId) private { //inject NONSTANDARD NAMING _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _REMOVETOKENFROMOWNERENUMERATION42(address from, uint256 tokenId) private { //inject NONSTANDARD NAMING // 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 = _ownedTokens[from].length.SUB290(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 _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } function _REMOVETOKENFROMALLTOKENSENUMERATION970(uint256 tokenId) private { //inject NONSTANDARD NAMING // 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.SUB290(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 _allTokens.length--; _allTokensIndex[tokenId] = 0; } } contract OveridableERC721Metadata is Context, ERC165, NoMintERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant _interface_id_erc721_metadata259 = 0x5b5e139f; //inject NONSTANDARD NAMING constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _REGISTERINTERFACE617(_interface_id_erc721_metadata259); } function NAME560() external view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL235() external view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function TOKENURI443(uint256 tokenId) public view returns (string memory) { //inject NONSTANDARD NAMING require(_EXISTS310(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } function _SETTOKENURI639(uint256 tokenId, string memory uri) internal { //inject NONSTANDARD NAMING require(_EXISTS310(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._BURN381(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } contract GunToken is NoMintERC721, NoMintERC721Enumerable, OveridableERC721Metadata, Ownable { using strings for *; address internal factory; uint16 public constant maxallocation33 = 4000; //inject NONSTANDARD NAMING uint256 public lastAllocation = 0; event BATCHTRANSFER76(address indexed from, address indexed to, uint256 indexed batchIndex); //inject NONSTANDARD NAMING struct Batch { address owner; uint16 size; uint8 category; uint256 startId; uint256 startTokenId; } Batch[] public allBatches; mapping(address => uint256) unactivatedBalance; mapping(uint256 => bool) isActivated; mapping(uint256 => bool) public outOfBatch; //Used for enumeration mapping(address => Batch[]) public batchesOwned; //Batch index to owner batch index mapping(uint256 => uint256) public ownedBatchIndex; mapping(uint8 => uint256) internal totalGunsMintedByCategory; uint256 internal _totalSupply; modifier ONLYFACTORY168 { //inject NONSTANDARD NAMING require(msg.sender == factory, "Not authorized"); _; } constructor(address factoryAddress) public OveridableERC721Metadata("WarRiders Gun", "WRG") { factory = factoryAddress; } function CATEGORYTYPETOID957(uint8 category, uint256 categoryId) public view returns (uint256) { //inject NONSTANDARD NAMING for (uint i = 0; i < allBatches.length; i++) { Batch memory a = allBatches[i]; if (a.category != category) continue; uint256 endId = a.startId + a.size; if (categoryId >= a.startId && categoryId < endId) { uint256 dif = categoryId - a.startId; return a.startTokenId + dif; } } revert(); } function FALLBACKCOUNT353(address __owner) public view returns (uint256) { //inject NONSTANDARD NAMING } function FALLBACKINDEX7(address __owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING } function MIGRATE859(uint256 count) public ONLYOWNER845 returns (uint256) { //inject NONSTANDARD NAMING //Empty for interface } function MIGRATESINGLE765() public ONLYOWNER845 returns (uint256) { //inject NONSTANDARD NAMING //Empty for interface } function RECOVERBATCH2175(uint256 index, uint256 tokenStart, uint256 tokenEnd) public ONLYOWNER845 { //inject NONSTANDARD NAMING } function MIGRATEBATCH628(uint256 index) public ONLYOWNER845 returns (uint256) { //inject NONSTANDARD NAMING } function RECOVERBATCH1434(uint256 index) public ONLYOWNER845 { //inject NONSTANDARD NAMING } function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING return TOKENOFOWNER723(owner)[index]; } function GETBATCHCOUNT927(address owner) public view returns(uint256) { //inject NONSTANDARD NAMING return batchesOwned[owner].length; } function UPDATEGUNFACTORY282(address _factory) public ONLYOWNER845 { //inject NONSTANDARD NAMING } function GETTOKENSINBATCH347(address owner, uint256 index) public view returns (uint256[] memory) { //inject NONSTANDARD NAMING Batch memory a = batchesOwned[owner][index]; uint256[] memory result = new uint256[](a.size); uint256 pos = 0; uint end = a.startTokenId + a.size; for (uint i = a.startTokenId; i < end; i++) { if (isActivated[i] && super.OWNEROF501(i) != owner) { continue; } result[pos] = i; pos++; } require(pos > 0); uint256 subAmount = a.size - pos; assembly { mstore(result, sub(mload(result), subAmount)) } return result; } function TOKENBYINDEX294(uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING return ALLTOKENS936()[index]; } function ALLTOKENS936() public view returns (uint256[] memory) { //inject NONSTANDARD NAMING uint256[] memory result = new uint256[](TOTALSUPPLY60()); uint pos = 0; for (uint i = 0; i < allBatches.length; i++) { Batch memory a = allBatches[i]; uint end = a.startTokenId + a.size; for (uint j = a.startTokenId; j < end; j++) { result[pos] = j; pos++; } } return result; } function TOKENOFOWNER723(address owner) public view returns (uint256[] memory) { //inject NONSTANDARD NAMING uint256[] memory result = new uint256[](BALANCEOF194(owner)); uint pos = 0; for (uint i = 0; i < batchesOwned[owner].length; i++) { Batch memory a = batchesOwned[owner][i]; uint end = a.startTokenId + a.size; for (uint j = a.startTokenId; j < end; j++) { if (isActivated[j] && super.OWNEROF501(j) != owner) { continue; } result[pos] = j; pos++; } } uint256[] memory fallbackOwned = _TOKENSOFOWNER469(owner); for (uint i = 0; i < fallbackOwned.length; i++) { result[pos] = fallbackOwned[i]; pos++; } return result; } function BALANCEOF194(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING require(owner != address(0), "ERC721: balance query for the zero address"); return super.BALANCEOF194(owner) + unactivatedBalance[owner]; } function OWNEROF501(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING require(EXISTS127(tokenId), "Token doesn't exist!"); if (isActivated[tokenId]) { return super.OWNEROF501(tokenId); } uint256 index = GETBATCHINDEX786(tokenId); require(index < allBatches.length, "Token batch doesn't exist"); Batch memory a = allBatches[index]; require(tokenId < a.startTokenId + a.size); return a.owner; } function EXISTS127(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING if (isActivated[_tokenId]) { return super._EXISTS310(_tokenId); } else { uint256 index = GETBATCHINDEX786(_tokenId); if (index < allBatches.length) { Batch memory a = allBatches[index]; uint end = a.startTokenId + a.size; return _tokenId < end; } return false; } } function TOTALSUPPLY60() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function CLAIMALLOCATION316(address to, uint16 size, uint8 category) public ONLYFACTORY168 returns (uint) { //inject NONSTANDARD NAMING require(size < maxallocation33, "Size must be smaller than maxAllocation"); allBatches.push(Batch({ owner: to, size: size, category: category, startId: totalGunsMintedByCategory[category], startTokenId: lastAllocation })); uint end = lastAllocation + size; for (uint i = lastAllocation; i < end; i++) { emit TRANSFER150(address(0), to, i); } lastAllocation += maxallocation33; unactivatedBalance[to] += size; totalGunsMintedByCategory[category] += size; _ADDBATCHTOOWNER461(to, allBatches[allBatches.length - 1]); _totalSupply += size; return lastAllocation; } function TRANSFERFROM196(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING if (!isActivated[tokenId]) { ACTIVATE8(tokenId); } super.TRANSFERFROM196(from, to, tokenId); } function ACTIVATE8(uint256 tokenId) public { //inject NONSTANDARD NAMING require(!isActivated[tokenId], "Token already activated"); uint256 index = GETBATCHINDEX786(tokenId); require(index < allBatches.length, "Token batch doesn't exist"); Batch memory a = allBatches[index]; require(tokenId < a.startTokenId + a.size); isActivated[tokenId] = true; ADDTOKENTO758(a.owner, tokenId); unactivatedBalance[a.owner]--; } function GETBATCHINDEX786(uint256 tokenId) public pure returns (uint256) { //inject NONSTANDARD NAMING uint256 index = (tokenId / maxallocation33); return index; } function CATEGORYFORTOKEN792(uint256 tokenId) public view returns (uint8) { //inject NONSTANDARD NAMING uint256 index = GETBATCHINDEX786(tokenId); require(index < allBatches.length, "Token batch doesn't exist"); Batch memory a = allBatches[index]; return a.category; } function CATEGORYIDFORTOKEN949(uint256 tokenId) public view returns (uint256) { //inject NONSTANDARD NAMING uint256 index = GETBATCHINDEX786(tokenId); require(index < allBatches.length, "Token batch doesn't exist"); Batch memory a = allBatches[index]; uint256 categoryId = (tokenId % maxallocation33) + a.startId; return categoryId; } function UINTTOSTRING328(uint v) internal pure returns (string memory) { //inject NONSTANDARD NAMING if (v == 0) { return "0"; } uint j = v; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (v != 0) { bstr[k--] = byte(uint8(48 + v % 10)); v /= 10; } return string(bstr); } function TOKENURI443(uint256 tokenId) public view returns (string memory) { //inject NONSTANDARD NAMING require(EXISTS127(tokenId), "Token doesn't exist!"); if (isActivated[tokenId]) { return super.TOKENURI443(tokenId); } else { //Predict the token URI uint8 category = CATEGORYFORTOKEN792(tokenId); uint256 _categoryId = CATEGORYIDFORTOKEN949(tokenId); string memory id = UINTTOSTRING328(category).TOSLICE667().CONCAT154("/".TOSLICE667()).TOSLICE667().CONCAT154(UINTTOSTRING328(_categoryId).TOSLICE667().CONCAT154(".json".TOSLICE667()).TOSLICE667()); string memory _base = "https://vault.warriders.com/guns/"; //Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json string memory _metadata = _base.TOSLICE667().CONCAT154(id.TOSLICE667()); return _metadata; } } function ADDTOKENTO758(address _to, uint256 _tokenId) internal { //inject NONSTANDARD NAMING //Predict the token URI uint8 category = CATEGORYFORTOKEN792(_tokenId); uint256 _categoryId = CATEGORYIDFORTOKEN949(_tokenId); string memory id = UINTTOSTRING328(category).TOSLICE667().CONCAT154("/".TOSLICE667()).TOSLICE667().CONCAT154(UINTTOSTRING328(_categoryId).TOSLICE667().CONCAT154(".json".TOSLICE667()).TOSLICE667()); string memory _base = "https://vault.warriders.com/guns/"; //Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json string memory _metadata = _base.TOSLICE667().CONCAT154(id.TOSLICE667()); super._ADDTOKENTO735(_to, _tokenId); super._SETTOKENURI639(_tokenId, _metadata); } function CEIL247(uint a, uint m) internal pure returns (uint ) { //inject NONSTANDARD NAMING return ((a + m - 1) / m) * m; } function _REMOVEBATCHFROMOWNER136(address from, Batch memory batch) private { //inject NONSTANDARD NAMING // 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 globalIndex = GETBATCHINDEX786(batch.startTokenId); uint256 lastBatchIndex = batchesOwned[from].length.SUB290(1); uint256 batchIndex = ownedBatchIndex[globalIndex]; // When the token to delete is the last token, the swap operation is unnecessary if (batchIndex != lastBatchIndex) { Batch memory lastBatch = batchesOwned[from][lastBatchIndex]; uint256 lastGlobalIndex = GETBATCHINDEX786(lastBatch.startTokenId); batchesOwned[from][batchIndex] = lastBatch; // Move the last batch to the slot of the to-delete batch ownedBatchIndex[lastGlobalIndex] = batchIndex; // Update the moved batch's index } // This also deletes the contents at the last position of the array batchesOwned[from].length--; // Note that ownedBatchIndex[batch] hasn't been cleared: it still points to the old slot (now occupied by // lastBatch, or just over the end of the array if the batch was the last one). } function _ADDBATCHTOOWNER461(address to, Batch memory batch) private { //inject NONSTANDARD NAMING uint256 globalIndex = GETBATCHINDEX786(batch.startTokenId); ownedBatchIndex[globalIndex] = batchesOwned[to].length; batchesOwned[to].push(batch); } function BATCHTRANSFER268(uint256 batchIndex, address to) public { //inject NONSTANDARD NAMING Batch storage a = allBatches[batchIndex]; address previousOwner = a.owner; require(a.owner == msg.sender); _REMOVEBATCHFROMOWNER136(previousOwner, a); a.owner = to; _ADDBATCHTOOWNER461(to, a); emit BATCHTRANSFER76(previousOwner, to, batchIndex); //Now to need to emit a bunch of transfer events uint end = a.startTokenId + a.size; uint256 unActivated = 0; for (uint i = a.startTokenId; i < end; i++) { if (isActivated[i]) { if (OWNEROF501(i) != previousOwner) continue; //The previous owner didn't own this token, don't emit an event } else { unActivated++; } emit TRANSFER150(previousOwner, to, i); } unactivatedBalance[to] += unActivated; unactivatedBalance[previousOwner] -= unActivated; } } contract ApproveAndCallFallBack { function RECEIVEAPPROVAL438(address from, uint256 tokens, address token, bytes memory data) public payable returns (bool); //inject NONSTANDARD NAMING } contract ERC20Basic { function TOTALSUPPLY60() public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF194(address who) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER702(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event TRANSFER150(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING } contract ERC20 is ERC20Basic { function ALLOWANCE798(address owner, address spender) //inject NONSTANDARD NAMING public view returns (uint256); function TRANSFERFROM196(address from, address to, uint256 value) //inject NONSTANDARD NAMING public returns (bool); function APPROVE594(address spender, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event APPROVAL578( //inject NONSTANDARD NAMING address indexed owner, address indexed spender, uint256 value ); } contract BurnableToken is ERC20 { event BURN595(address indexed burner, uint256 value); //inject NONSTANDARD NAMING function BURN840(uint256 _value) public; //inject NONSTANDARD NAMING } contract StandardBurnableToken is BurnableToken { function BURNFROM813(address _from, uint256 _value) public; //inject NONSTANDARD NAMING } interface BZNFeed { function CONVERT77(uint256 usd) external view returns (uint256); //inject NONSTANDARD NAMING } contract SimpleBZNFeed is BZNFeed, Ownable { uint256 private conversion; function UPDATECONVERSION150(uint256 conversionRate) public ONLYOWNER845 { //inject NONSTANDARD NAMING conversion = conversionRate; } function CONVERT77(uint256 usd) external view returns (uint256) { //inject NONSTANDARD NAMING return usd * conversion; } } interface IDSValue { function PEEK123() external view returns (bytes32, bool); //inject NONSTANDARD NAMING function READ988() external view returns (bytes32); //inject NONSTANDARD NAMING function POKE435(bytes32 wut) external; //inject NONSTANDARD NAMING function VOID212() external; //inject NONSTANDARD NAMING } library BytesLib { function CONCAT154( //inject NONSTANDARD NAMING bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function CONCATSTORAGE572(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function SLICE625( //inject NONSTANDARD NAMING bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function TOADDRESS210(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function TOUINT8119(bytes memory _bytes, uint _start) internal pure returns (uint8) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function TOUINT16152(bytes memory _bytes, uint _start) internal pure returns (uint16) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function TOUINT32393(bytes memory _bytes, uint _start) internal pure returns (uint32) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function TOUINT64646(bytes memory _bytes, uint _start) internal pure returns (uint64) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function TOUINT96427(bytes memory _bytes, uint _start) internal pure returns (uint96) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function TOUINT12878(bytes memory _bytes, uint _start) internal pure returns (uint128) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function TOUINT505(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function TOBYTES32154(bytes memory _bytes, uint _start) internal pure returns (bytes32) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function EQUAL770(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function EQUALSTORAGE902( //inject NONSTANDARD NAMING bytes storage _preBytes, bytes memory _postBytes ) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } } contract GunPreOrder is Ownable, ApproveAndCallFallBack { using BytesLib for bytes; using SafeMath for uint256; //Event for when a bulk buy order has been placed event CONSUMERBULKBUY355(uint8 category, uint256 quanity, address reserver); //inject NONSTANDARD NAMING //Event for when a gun has been bought event GUNSBOUGHT917(uint256 gunId, address owner, uint8 category); //inject NONSTANDARD NAMING //Event for when ether is taken out of this contract event WITHDRAWAL910(uint256 amount); //inject NONSTANDARD NAMING //Default referal commision percent uint256 public constant commission_percent82 = 5; //inject NONSTANDARD NAMING //Whether category is open mapping(uint8 => bool) public categoryExists; mapping(uint8 => bool) public categoryOpen; mapping(uint8 => bool) public categoryKilled; //The additional referal commision percent for any given referal address (default is 0) mapping(address => uint256) internal commissionRate; //How many guns in a given category an address has reserved mapping(uint8 => mapping(address => uint256)) public categoryReserveAmount; //Opensea buy address address internal constant opensea308 = 0x5b3256965e7C3cF26E11FCAf296DfC8807C01073; //inject NONSTANDARD NAMING //The percent increase and percent base for a given category mapping(uint8 => uint256) public categoryPercentIncrease; mapping(uint8 => uint256) public categoryPercentBase; //Price of a givevn category in USD WEI mapping(uint8 => uint256) public categoryPrice; //The percent of ether required for buying in BZN mapping(uint8 => uint256) public requiredEtherPercent; mapping(uint8 => uint256) public requiredEtherPercentBase; bool public allowCreateCategory = true; //The gun token contract GunToken public token; //The gun factory contract GunFactory internal factory; //The BZN contract StandardBurnableToken internal bzn; //The Maker ETH/USD price feed IDSValue public ethFeed; BZNFeed public bznFeed; //The gamepool address address internal gamePool; //Require the skinned/regular shop to be opened modifier ENSURESHOPOPEN328(uint8 category) { //inject NONSTANDARD NAMING require(categoryExists[category], "Category doesn't exist!"); require(categoryOpen[category], "Category is not open!"); _; } //Allow a function to accept ETH payment modifier PAYINETH352(address referal, uint8 category, address new_owner, uint16 quanity) { //inject NONSTANDARD NAMING uint256 usdPrice; uint256 totalPrice; (usdPrice, totalPrice) = PRICEFOR73(category, quanity); require(usdPrice > 0, "Price not yet set"); categoryPrice[category] = usdPrice; //Save last price uint256 price = CONVERT77(totalPrice, false); require(msg.value >= price, "Not enough Ether sent!"); _; if (msg.value > price) { uint256 change = msg.value - price; msg.sender.transfer(change); } if (referal != address(0)) { require(referal != msg.sender, "The referal cannot be the sender"); require(referal != tx.origin, "The referal cannot be the tranaction origin"); require(referal != new_owner, "The referal cannot be the new owner"); //The commissionRate map adds any partner bonuses, or 0 if a normal user referral uint256 totalCommision = commission_percent82 + commissionRate[referal]; uint256 commision = (price * totalCommision) / 100; address payable _referal = address(uint160(referal)); _referal.transfer(commision); } } //Allow function to accept BZN payment modifier PAYINBZN388(address referal, uint8 category, address payable new_owner, uint16 quanity) { //inject NONSTANDARD NAMING uint256[] memory prices = new uint256[](4); //Hack to work around local var limit (usdPrice, bznPrice, commision, totalPrice) (prices[0], prices[3]) = PRICEFOR73(category, quanity); require(prices[0] > 0, "Price not yet set"); categoryPrice[category] = prices[0]; prices[1] = CONVERT77(prices[3], true); //Convert the totalPrice to BZN //The commissionRate map adds any partner bonuses, or 0 if a normal user referral if (referal != address(0)) { prices[2] = (prices[1] * (commission_percent82 + commissionRate[referal])) / 100; } uint256 requiredEther = (CONVERT77(prices[3], false) * requiredEtherPercent[category]) / requiredEtherPercentBase[category]; require(msg.value >= requiredEther, "Buying with BZN requires some Ether!"); bzn.BURNFROM813(new_owner, (((prices[1] - prices[2]) * 30) / 100)); bzn.TRANSFERFROM196(new_owner, gamePool, prices[1] - prices[2] - (((prices[1] - prices[2]) * 30) / 100)); _; if (msg.value > requiredEther) { new_owner.transfer(msg.value - requiredEther); } if (referal != address(0)) { require(referal != msg.sender, "The referal cannot be the sender"); require(referal != tx.origin, "The referal cannot be the tranaction origin"); require(referal != new_owner, "The referal cannot be the new owner"); bzn.TRANSFERFROM196(new_owner, referal, prices[2]); prices[2] = (requiredEther * (commission_percent82 + commissionRate[referal])) / 100; address payable _referal = address(uint160(referal)); _referal.transfer(prices[2]); } } //Constructor constructor( address tokenAddress, address tokenFactory, address gp, address isd, address bzn_address ) public { token = GunToken(tokenAddress); factory = GunFactory(tokenFactory); ethFeed = IDSValue(isd); bzn = StandardBurnableToken(bzn_address); gamePool = gp; //Set percent increases categoryPercentIncrease[1] = 100035; categoryPercentBase[1] = 100000; categoryPercentIncrease[2] = 100025; categoryPercentBase[2] = 100000; categoryPercentIncrease[3] = 100015; categoryPercentBase[3] = 100000; commissionRate[opensea308] = 10; } function CREATECATEGORY817(uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(allowCreateCategory); categoryExists[category] = true; } function DISABLECREATECATEGORIES112() public ONLYOWNER845 { //inject NONSTANDARD NAMING allowCreateCategory = false; } //Set the referal commision rate for an address function SETCOMMISSION914(address referral, uint256 percent) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(percent > commission_percent82); require(percent < 95); percent = percent - commission_percent82; commissionRate[referral] = percent; } //Set the price increase/base for skinned or regular guns function SETPERCENTINCREASE775(uint256 increase, uint256 base, uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(increase > base); categoryPercentIncrease[category] = increase; categoryPercentBase[category] = base; } function SETETHERPERCENT411(uint256 percent, uint256 base, uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING requiredEtherPercent[category] = percent; requiredEtherPercentBase[category] = base; } function KILLCATEGORY428(uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(!categoryKilled[category]); categoryOpen[category] = false; categoryKilled[category] = true; } //Open/Close the skinned or regular guns shop function SETSHOPSTATE191(uint8 category, bool open) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(category == 1 || category == 2 || category == 3); require(!categoryKilled[category]); require(categoryExists[category]); categoryOpen[category] = open; } function SETPRICE360(uint8 category, uint256 price, bool inWei) public ONLYOWNER845 { //inject NONSTANDARD NAMING uint256 multiply = 1e18; if (inWei) { multiply = 1; } categoryPrice[category] = price * multiply; } function WITHDRAW154(uint256 amount) public ONLYOWNER845 { //inject NONSTANDARD NAMING uint256 balance = address(this).balance; require(amount <= balance, "Requested to much"); address payable _owner = address(uint160(OWNER824())); _owner.transfer(amount); emit WITHDRAWAL910(amount); } function SETBZNFEEDCONTRACT654(address new_bzn_feed) public ONLYOWNER845 { //inject NONSTANDARD NAMING bznFeed = BZNFeed(new_bzn_feed); } //Buy many skinned or regular guns with BZN. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free function BUYWITHBZN846(address referal, uint8 category, address payable new_owner, uint16 quanity) ENSURESHOPOPEN328(category) PAYINBZN388(referal, category, new_owner, quanity) public payable returns (bool) { //inject NONSTANDARD NAMING factory.MINTFOR528(new_owner, quanity, category); return true; } //Buy many skinned or regular guns with ETH. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free function BUYWITHETHER108(address referal, uint8 category, address new_owner, uint16 quanity) ENSURESHOPOPEN328(category) PAYINETH352(referal, category, new_owner, quanity) public payable returns (bool) { //inject NONSTANDARD NAMING factory.MINTFOR528(new_owner, quanity, category); return true; } function CONVERT77(uint256 usdValue, bool isBZN) public view returns (uint256) { //inject NONSTANDARD NAMING if (isBZN) { return bznFeed.CONVERT77(usdValue); } else { bool temp; bytes32 aaa; (aaa, temp) = ethFeed.PEEK123(); uint256 priceForEtherInUsdWei = uint256(aaa); return usdValue / (priceForEtherInUsdWei / 1e18); } } function PRICEFOR73(uint8 category, uint16 quanity) public view returns (uint256, uint256) { //inject NONSTANDARD NAMING require(quanity > 0); uint256 percent = categoryPercentIncrease[category]; uint256 base = categoryPercentBase[category]; uint256 currentPrice = categoryPrice[category]; uint256 nextPrice = currentPrice; uint256 totalPrice = 0; //We can't use exponents because we'll overflow quickly //Only for loop :( for (uint i = 0; i < quanity; i++) { nextPrice = (currentPrice * percent) / base; currentPrice = nextPrice; totalPrice += nextPrice; } //Return the next price, as this is the true price return (nextPrice, totalPrice); } //Determine if a tokenId exists (has been sold) function SOLD957(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING return token.EXISTS127(_tokenId); } function RECEIVEAPPROVAL438(address from, uint256 tokenAmount, address tokenContract, bytes memory data) public payable returns (bool) { //inject NONSTANDARD NAMING address referal; uint8 category; uint16 quanity; (referal, category, quanity) = abi.decode(data, (address, uint8, uint16)); require(quanity >= 1); address payable _from = address(uint160(from)); BUYWITHBZN846(referal, category, _from, quanity); return true; } } contract GunFactory is Ownable { using strings for *; uint8 public constant premium_category760 = 1; //inject NONSTANDARD NAMING uint8 public constant midgrade_category818 = 2; //inject NONSTANDARD NAMING uint8 public constant regular_category63 = 3; //inject NONSTANDARD NAMING uint256 public constant one_month568 = 2628000; //inject NONSTANDARD NAMING uint256 public mintedGuns = 0; address preOrderAddress; GunToken token; mapping(uint8 => uint256) internal gunsMintedByCategory; mapping(uint8 => uint256) internal totalGunsMintedByCategory; mapping(uint8 => uint256) internal firstMonthLimit; mapping(uint8 => uint256) internal secondMonthLimit; mapping(uint8 => uint256) internal thirdMonthLimit; uint256 internal startTime; mapping(uint8 => uint256) internal currentMonthEnd; uint256 internal monthOneEnd; uint256 internal monthTwoEnd; modifier ONLYPREORDER406 { //inject NONSTANDARD NAMING require(msg.sender == preOrderAddress, "Not authorized"); _; } modifier ISINITIALIZED13 { //inject NONSTANDARD NAMING require(preOrderAddress != address(0), "No linked preorder"); require(address(token) != address(0), "No linked token"); _; } constructor() public { firstMonthLimit[premium_category760] = 5000; firstMonthLimit[midgrade_category818] = 20000; firstMonthLimit[regular_category63] = 30000; secondMonthLimit[premium_category760] = 2500; secondMonthLimit[midgrade_category818] = 10000; secondMonthLimit[regular_category63] = 15000; thirdMonthLimit[premium_category760] = 600; thirdMonthLimit[midgrade_category818] = 3000; thirdMonthLimit[regular_category63] = 6000; startTime = block.timestamp; monthOneEnd = startTime + one_month568; monthTwoEnd = startTime + one_month568 + one_month568; currentMonthEnd[premium_category760] = monthOneEnd; currentMonthEnd[midgrade_category818] = monthOneEnd; currentMonthEnd[regular_category63] = monthOneEnd; } function UINTTOSTRING328(uint v) internal pure returns (string memory) { //inject NONSTANDARD NAMING if (v == 0) { return "0"; } uint j = v; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (v != 0) { bstr[k--] = byte(uint8(48 + v % 10)); v /= 10; } return string(bstr); } function MINTFOR528(address newOwner, uint16 size, uint8 category) public ONLYPREORDER406 ISINITIALIZED13 returns (uint256) { //inject NONSTANDARD NAMING GunPreOrder preOrder = GunPreOrder(preOrderAddress); require(preOrder.categoryExists(category), "Invalid category"); require(!HASREACHEDLIMIT199(category), "The monthly limit has been reached"); token.CLAIMALLOCATION316(newOwner, size, category); mintedGuns++; gunsMintedByCategory[category] = gunsMintedByCategory[category] + 1; totalGunsMintedByCategory[category] = totalGunsMintedByCategory[category] + 1; } function HASREACHEDLIMIT199(uint8 category) internal returns (bool) { //inject NONSTANDARD NAMING uint256 currentTime = block.timestamp; uint256 limit = CURRENTLIMIT394(category); uint256 monthEnd = currentMonthEnd[category]; //If the current block time is greater than or equal to the end of the month if (currentTime >= monthEnd) { //It's a new month, reset all limits //gunsMintedByCategory[PREMIUM_CATEGORY] = 0; //gunsMintedByCategory[MIDGRADE_CATEGORY] = 0; //gunsMintedByCategory[REGULAR_CATEGORY] = 0; gunsMintedByCategory[category] = 0; //Set next month end to be equal one month in advance //do this while the current time is greater than the next month end while (currentTime >= monthEnd) { monthEnd = monthEnd + one_month568; } //Finally, update the limit limit = CURRENTLIMIT394(category); currentMonthEnd[category] = monthEnd; } //Check if the limit has been reached return gunsMintedByCategory[category] >= limit; } function REACHEDLIMIT389(uint8 category) public view returns (bool) { //inject NONSTANDARD NAMING uint256 limit = CURRENTLIMIT394(category); return gunsMintedByCategory[category] >= limit; } function CURRENTLIMIT394(uint8 category) public view returns (uint256) { //inject NONSTANDARD NAMING uint256 currentTime = block.timestamp; uint256 limit; if (currentTime < monthOneEnd) { limit = firstMonthLimit[category]; } else if (currentTime < monthTwoEnd) { limit = secondMonthLimit[category]; } else { limit = thirdMonthLimit[category]; } return limit; } function SETCATEGORYLIMIT220(uint8 category, uint256 firstLimit, uint256 secondLimit, uint256 thirdLimit) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(firstMonthLimit[category] == 0); require(secondMonthLimit[category] == 0); require(thirdMonthLimit[category] == 0); firstMonthLimit[category] = firstLimit; secondMonthLimit[category] = secondLimit; thirdMonthLimit[category] = thirdLimit; } function ATTACHPREORDER925(address dst) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(preOrderAddress == address(0)); require(dst != address(0)); //Enforce that address is indeed a preorder GunPreOrder preOrder = GunPreOrder(dst); preOrderAddress = address(preOrder); } function ATTACHTOKEN953(address dst) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(address(token) == address(0)); require(dst != address(0)); //Enforce that address is indeed a preorder GunToken ct = GunToken(dst); token = ct; } }
inject NONSTANDARD NAMING
function TOUINT64646(bytes memory _bytes, uint _start) internal pure returns (uint64) {
6,431,973
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.6.12; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./MToken.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/ExponentialNoError.sol"; import "./Utils/AssetHelpers.sol"; import "./Moartroller.sol"; import "./SimplePriceOracle.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract LiquidityMathModelV1 is LiquidityMathModelInterface, LiquidityMathModelErrorReporter, ExponentialNoError, Ownable, AssetHelpers { /** * @notice get the maximum asset value that can be still optimized. * @notice if protectionId is supplied, the maxOptimizableValue is increased by the protection lock value' * which is helpful to recalculate how much of this protection can be optimized again */ function getMaxOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) external override view returns (uint){ uint returnValue; uint hypotheticalOptimizableValue = getHypotheticalOptimizableValue(arguments); uint totalProtectionLockedValue; (totalProtectionLockedValue, ) = getTotalProtectionLockedValue(arguments); if(hypotheticalOptimizableValue <= totalProtectionLockedValue){ returnValue = 0; } else{ returnValue = sub_(hypotheticalOptimizableValue, totalProtectionLockedValue); } return returnValue; } /** * @notice get the maximum value of an asset that can be optimized by protection for the given user * @dev optimizable = asset value * MPC * @return the hypothetical optimizable value * TODO: replace hardcoded 1e18 values */ function getHypotheticalOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint) { uint assetValue = div_( mul_( div_( mul_( arguments.asset.balanceOf(arguments.account), arguments.asset.exchangeRateStored() ), 1e18 ), arguments.oracle.getUnderlyingPrice(arguments.asset) ), getAssetDecimalsMantissa(arguments.asset.getUnderlying()) ); uint256 hypotheticalOptimizableValue = div_( mul_( assetValue, arguments.asset.maxProtectionComposition() ), arguments.asset.maxProtectionCompositionMantissa() ); return hypotheticalOptimizableValue; } /** * @dev gets all locked protections values with mark to market value. Used by Moartroller. */ function getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint, uint) { uint _lockedValue = 0; uint _markToMarket = 0; uint _protectionCount = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(arguments.account, arguments.asset.underlying()); for (uint j = 0; j < _protectionCount; j++) { uint protectionId = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrency(arguments.account, arguments.asset.underlying(), j); bool protectionIsAlive = arguments.cprotection.isProtectionAlive(protectionId); if(protectionIsAlive){ _lockedValue = add_(_lockedValue, arguments.cprotection.getUnderlyingProtectionLockedValue(protectionId)); uint assetSpotPrice = arguments.oracle.getUnderlyingPrice(arguments.asset); uint protectionStrikePrice = arguments.cprotection.getUnderlyingStrikePrice(protectionId); if( assetSpotPrice > protectionStrikePrice) { _markToMarket = _markToMarket + div_( mul_( div_( mul_( assetSpotPrice - protectionStrikePrice, arguments.cprotection.getUnderlyingProtectionLockedAmount(protectionId) ), getAssetDecimalsMantissa(arguments.asset.underlying()) ), arguments.collateralFactorMantissa ), 1e18 ); } } } return (_lockedValue , _markToMarket); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.6.12; import "../MToken.sol"; import "../MProtection.sol"; import "../Interfaces/PriceOracle.sol"; interface LiquidityMathModelInterface { struct LiquidityMathArgumentsSet { MToken asset; address account; uint collateralFactorMantissa; MProtection cprotection; PriceOracle oracle; } function getMaxOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns (uint); function getHypotheticalOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint); function getTotalProtectionLockedValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint, uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Utils/ErrorReporter.sol"; import "./Utils/Exponential.sol"; import "./Interfaces/EIP20Interface.sol"; import "./MTokenStorage.sol"; import "./Interfaces/MTokenInterface.sol"; import "./Interfaces/MProxyInterface.sol"; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; /** * @title MOAR's MToken Contract * @notice Abstract base for MTokens * @author MOAR */ abstract contract MToken is MTokenInterface, Exponential, TokenErrorReporter, MTokenStorage { /** * @notice Indicator that this is a MToken contract (for inspection) */ bool public constant isMToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address MTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when moartroller is changed */ event NewMoartroller(Moartroller oldMoartroller, Moartroller newMoartroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModelInterface oldInterestRateModel, InterestRateModelInterface newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /** * @notice Max protection composition value updated event */ event MpcUpdated(uint newValue); /** * @notice Initialize the money market * @param moartroller_ The address of the Moartroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function init(Moartroller moartroller_, AbstractInterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "not_admin"); require(accrualBlockNumber == 0 && borrowIndex == 0, "already_init"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "too_low"); // Set the moartroller uint err = _setMoartroller(moartroller_); require(err == uint(Error.NO_ERROR), "setting moartroller failed"); // Initialize block number and borrow index (block number mocks depend on moartroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting IRM failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; maxProtectionComposition = 5000; maxProtectionCompositionMantissa = 1e4; reserveFactorMaxMantissa = 1e18; borrowRateMaxMantissa = 0.0005e16; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = moartroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.TRANSFER_MOARTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srmTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srmTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srmTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); // unused function // moartroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external virtual override nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external virtual override nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external virtual override returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external virtual override view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external virtual override view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external virtual override returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance_calculation_failed"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by moartroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external virtual override view returns (uint, uint, uint, uint) { uint mTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), mTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this mToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external virtual override view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this mToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external virtual override view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external virtual override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external virtual override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public virtual view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public virtual nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the MToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public virtual view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the MToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this mToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external virtual override view returns (uint) { return getCashPrior(); } function getRealBorrowIndex() public view returns (uint) { uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calc block delta"); Exp memory simpleInterestFactor; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); require(mathErr == MathError.NO_ERROR, "could not calc simpleInterestFactor"); (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); require(mathErr == MathError.NO_ERROR, "could not calc borrowIndex"); return borrowIndexNew; } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public virtual returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calc block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; AccrueInterestTempStorage memory temp; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.totalBorrowsNew) = addUInt(temp.interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.reservesAdded) = mulScalarTruncate(Exp({mantissa: reserveFactorMantissa}), temp.interestAccumulated); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.splitedReserves_2) = mulScalarTruncate(Exp({mantissa: reserveSplitFactorMantissa}), temp.reservesAdded); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.splitedReserves_1) = subUInt(temp.reservesAdded, temp.splitedReserves_2); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.totalReservesNew) = addUInt(temp.splitedReserves_1, reservesPrior); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = temp.borrowIndexNew; totalBorrows = temp.totalBorrowsNew; totalReserves = temp.totalReservesNew; if(temp.splitedReserves_2 > 0){ address mProxy = moartroller.mProxy(); EIP20Interface(underlying).approve(mProxy, temp.splitedReserves_2); MProxyInterface(mProxy).proxySplitReserves(underlying, temp.splitedReserves_2); } /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, temp.interestAccumulated, temp.borrowIndexNew, temp.totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives mTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives mTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = moartroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.MINT_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the mToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of mTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); /* * We calculate the new total supply of mTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ // unused function // moartroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems mTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of mTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems mTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming mTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems mTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of mTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming mTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeemFresh_missing_zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } /* Fail if user tries to redeem more than he has locked with c-op*/ // TODO: update error codes uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18); if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ moartroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } function borrowForInternal(address payable borrower, uint borrowAmount) internal nonReentrant returns (uint) { require(moartroller.isPrivilegedAddress(msg.sender), "permission_missing"); uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(borrower, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = moartroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.BORROW_MOARTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ //unused function // moartroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = moartroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REPAY_BORROW_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ /* If the borrow is repaid by another user -1 cannot be used to prevent borrow front-running */ if (repayAmount == uint(-1)) { require(tx.origin == borrower, "specify a precise amount"); vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // moartroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param mTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, MToken mTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = mTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, mTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param mTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, MToken mTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = moartroller.liquidateBorrowAllowed(address(this), address(mTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify mTokenCollateral market's block number equals current block number */ if (mTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = moartroller.liquidateCalculateSeizeUserTokens(address(this), address(mTokenCollateral), actualRepayAmount, borrower); require(amountSeizeError == uint(Error.NO_ERROR), "CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(mTokenCollateral.balanceOf(borrower) >= seizeTokens, "TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(mTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = mTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(mTokenCollateral), seizeTokens); /* We call the defense hook */ // unused function // moartroller.liquidateBorrowVerify(address(this), address(mTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another mToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of mTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external virtual override nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another MToken. * Its absolutely critical to use msg.sender as the seizer mToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed mToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of mTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = moartroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ // unused function // moartroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external virtual override returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external virtual override returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new moartroller for the market * @dev Admin function to set a new moartroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMoartroller(Moartroller newMoartroller) public virtual returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MOARTROLLER_OWNER_CHECK); } Moartroller oldMoartroller = moartroller; // Ensure invoke moartroller.isMoartroller() returns true require(newMoartroller.isMoartroller(), "not_moartroller"); // Set market's moartroller to newMoartroller moartroller = newMoartroller; // Emit NewMoartroller(oldMoartroller, newMoartroller) emit NewMoartroller(oldMoartroller, newMoartroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external virtual override nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } function _setReserveSplitFactor(uint newReserveSplitFactorMantissa) external nonReentrant returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } reserveSplitFactorMantissa = newReserveSplitFactorMantissa; return uint(Error.NO_ERROR); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external virtual override nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(AbstractInterestRateModel newInterestRateModel) public virtual returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(AbstractInterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModelInterface oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "not_interest_model"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /** * @notice Sets new value for max protection composition parameter * @param newMPC New value of MPC * @return uint 0=success, otherwise a failure */ function _setMaxProtectionComposition(uint256 newMPC) external returns(uint){ if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } maxProtectionComposition = newMPC; emit MpcUpdated(newMPC); return uint(Error.NO_ERROR); } /** * @notice Returns address of underlying token * @return address of underlying token */ function getUnderlying() external override view returns(address){ return underlying; } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal virtual view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal virtual returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal virtual; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; contract MoartrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, MOARTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_PROTECTION_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, MOARTROLLER_REJECTION, MOARTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_MOARTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_MOARTROLLER_REJECTION, LIQUIDATE_MOARTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_MOARTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_MOARTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_MOARTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_MOARTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_MOARTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract LiquidityMathModelErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, PRICE_ERROR, SNAPSHOT_ERROR } enum FailureInfo { ORACLE_PRICE_CHECK_FAILED } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @title Exponential module for storing fixed-precision decimals * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "../Interfaces/EIP20Interface.sol"; contract AssetHelpers { /** * @dev return asset decimals mantissa. Returns 1e18 if ETH */ function getAssetDecimalsMantissa(address assetAddress) public view returns (uint256){ uint assetDecimals = 1e18; if (assetAddress != address(0)) { EIP20Interface token = EIP20Interface(assetAddress); assetDecimals = 10 ** uint256(token.decimals()); } return assetDecimals; } } // SPDX-License-Identifier: BSD-3-Clause // Thanks to Compound for their foundational work in DeFi and open-sourcing their code from which we build upon. pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; // import "hardhat/console.sol"; import "./MToken.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/ExponentialNoError.sol"; import "./Interfaces/PriceOracle.sol"; import "./Interfaces/MoartrollerInterface.sol"; import "./Interfaces/Versionable.sol"; import "./Interfaces/MProxyInterface.sol"; import "./MoartrollerStorage.sol"; import "./Governance/UnionGovernanceToken.sol"; import "./MProtection.sol"; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./LiquidityMathModelV1.sol"; import "./Utils/SafeEIP20.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Interfaces/LiquidationModelInterface.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title MOAR's Moartroller Contract * @author MOAR */ contract Moartroller is MoartrollerV6Storage, MoartrollerInterface, MoartrollerErrorReporter, ExponentialNoError, Versionable, Initializable { using SafeEIP20 for EIP20Interface; /// @notice Indicator that this is a Moartroller contract (for inspection) bool public constant isMoartroller = true; /// @notice Emitted when an admin supports a market event MarketListed(MToken mToken); /// @notice Emitted when an account enters a market event MarketEntered(MToken mToken, address account); /// @notice Emitted when an account exits a market event MarketExited(MToken mToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when protection is changed event NewCProtection(MProtection oldCProtection, MProtection newCProtection); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPausedMToken(MToken mToken, string action, bool pauseState); /// @notice Emitted when a new MOAR speed is calculated for a market event MoarSpeedUpdated(MToken indexed mToken, uint newSpeed); /// @notice Emitted when a new MOAR speed is set for a contributor event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed); /// @notice Emitted when MOAR is distributed to a supplier event DistributedSupplierMoar(MToken indexed mToken, address indexed supplier, uint moarDelta, uint moarSupplyIndex); /// @notice Emitted when MOAR is distributed to a borrower event DistributedBorrowerMoar(MToken indexed mToken, address indexed borrower, uint moarDelta, uint moarBorrowIndex); /// @notice Emitted when borrow cap for a mToken is changed event NewBorrowCap(MToken indexed mToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when MOAR is granted by admin event MoarGranted(address recipient, uint amount); event NewLiquidityMathModel(address oldLiquidityMathModel, address newLiquidityMathModel); event NewLiquidationModel(address oldLiquidationModel, address newLiquidationModel); /// @notice The initial MOAR index for a market uint224 public constant moarInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // Custom initializer function initialize(LiquidityMathModelInterface mathModel, LiquidationModelInterface lqdModel) public initializer { admin = msg.sender; liquidityMathModel = mathModel; liquidationModel = lqdModel; rewardClaimEnabled = false; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (MToken[] memory) { MToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param mToken The mToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, MToken mToken) external view returns (bool) { return markets[address(mToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param mTokens The list of addresses of the mToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory mTokens) public override returns (uint[] memory) { uint len = mTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { MToken mToken = MToken(mTokens[i]); results[i] = uint(addToMarketInternal(mToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param mToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(mToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(mToken); emit MarketEntered(mToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param mTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address mTokenAddress) external override returns (uint) { MToken mToken = MToken(mTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the mToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(mToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set mToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete mToken from the account’s list of assets */ // load into memory for faster iteration MToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == mToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 MToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.pop(); emit MarketExited(mToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param mToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address mToken, address minter, uint mintAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[mToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, minter); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param mToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of mTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external override returns (uint) { uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, redeemer); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[mToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param mToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external override { // Shh - currently unused mToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param mToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address mToken, address borrower, uint borrowAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[mToken], "borrow is paused"); if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[mToken].accountMembership[borrower]) { // only mTokens may call borrowAllowed if borrower not in market require(msg.sender == mToken, "sender must be mToken"); // attempt to add borrower to the market Error err = addToMarketInternal(MToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[mToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[mToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = MToken(mToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()}); updateMoarBorrowIndex(mToken, borrowIndex); distributeBorrowerMoar(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param mToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address mToken, address payer, address borrower, uint repayAmount) external override returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()}); updateMoarBorrowIndex(mToken, borrowIndex); distributeBorrowerMoar(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Checks if the liquidation should be allowed to occur * @param mTokenBorrowed Asset which was borrowed by the borrower * @param mTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint repayAmount) external override returns (uint) { // Shh - currently unused liquidator; if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Checks if the seizing of assets should be allowed to occur * @param mTokenCollateral Asset which was used as collateral and will be seized * @param mTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (MToken(mTokenCollateral).moartroller() != MToken(mTokenBorrowed).moartroller()) { return uint(Error.MOARTROLLER_MISMATCH); } // Keep the flywheel moving updateMoarSupplyIndex(mTokenCollateral); distributeSupplierMoar(mTokenCollateral, borrower); distributeSupplierMoar(mTokenCollateral, liquidator); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param mToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of mTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address mToken, address src, address dst, uint transferTokens) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(mToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, src); distributeSupplierMoar(mToken, dst); return uint(Error.NO_ERROR); } /*** Liquidity/Liquidation Calculations ***/ /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address mTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, MToken mTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in MToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { MToken asset = assets[i]; address _account = account; // Read the balances and exchange rate from the mToken (oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(_account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = mul_(Exp({mantissa: vars.oraclePriceMantissa}), 10**uint256(18 - EIP20Interface(asset.getUnderlying()).decimals())); // Pre-compute a conversion factor from tokens -> dai (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * mTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral); // Protection value calculation sumCollateral += protectionValueLocked // Mark to market value calculation sumCollateral += markToMarketValue uint protectionValueLocked; uint markToMarketValue; (protectionValueLocked, markToMarketValue) = liquidityMathModel.getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet(asset, _account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle)); if (vars.sumCollateral < mul_( protectionValueLocked, vars.collateralFactor)) { vars.sumCollateral = 0; } else { vars.sumCollateral = sub_(vars.sumCollateral, mul_( protectionValueLocked, vars.collateralFactor)); } vars.sumCollateral = add_(vars.sumCollateral, protectionValueLocked); vars.sumCollateral = add_(vars.sumCollateral, markToMarketValue); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with mTokenModify if (asset == mTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); _account = account; } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Returns the value of possible optimization left for asset * @param asset The MToken address * @param account The owner of asset * @return The value of possible optimization */ function getMaxOptimizableValue(MToken asset, address account) public view returns(uint){ return liquidityMathModel.getMaxOptimizableValue( LiquidityMathModelInterface.LiquidityMathArgumentsSet( asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle ) ); } /** * @notice Returns the value of hypothetical optimization (ignoring existing optimization used) for asset * @param asset The MToken address * @param account The owner of asset * @return The amount of hypothetical optimization */ function getHypotheticalOptimizableValue(MToken asset, address account) public view returns(uint){ return liquidityMathModel.getHypotheticalOptimizableValue( LiquidityMathModelInterface.LiquidityMathArgumentsSet( asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle ) ); } function liquidateCalculateSeizeUserTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount, address account) external override view returns (uint, uint) { return LiquidationModelInterface(liquidationModel).liquidateCalculateSeizeUserTokens( LiquidationModelInterface.LiquidateCalculateSeizeUserTokensArgumentsSet( oracle, this, mTokenBorrowed, mTokenCollateral, actualRepayAmount, account, liquidationIncentiveMantissa ) ); } /** * @notice Returns the amount of a specific asset that is locked under all c-ops * @param asset The MToken address * @param account The owner of asset * @return The amount of asset locked under c-ops */ function getUserLockedAmount(MToken asset, address account) public override view returns(uint) { uint protectionLockedAmount; address currency = asset.underlying(); uint256 numOfProtections = cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(account, currency); for (uint i = 0; i < numOfProtections; i++) { uint cProtectionId = cprotection.getUserUnderlyingProtectionTokenIdByCurrency(account, currency, i); if(cprotection.isProtectionAlive(cProtectionId)){ protectionLockedAmount = protectionLockedAmount + cprotection.getUnderlyingProtectionLockedAmount(cProtectionId); } } return protectionLockedAmount; } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the moartroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the moartroller PriceOracle oldOracle = oracle; // Set moartroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets a new CProtection that is allowed to use as a collateral optimisation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setProtection(address newCProtection) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } MProtection oldCProtection = cprotection; cprotection = MProtection(newCProtection); // Emit NewPriceOracle(oldOracle, newOracle) emit NewCProtection(oldCProtection, cprotection); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param mToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(mToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } // TODO: this check is temporary switched off. we can make exception for UNN later // Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // // // Check collateral factor <= 0.9 // Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); // if (lessThanExp(highLimit, newCollateralFactorExp)) { // return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); // } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } function _setRewardClaimEnabled(bool status) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); rewardClaimEnabled = status; return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param mToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(MToken mToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(mToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } mToken.isMToken(); // Sanity check to make sure its really a MToken // Note that isMoared is not in active use anymore markets[address(mToken)] = Market({isListed: true, isMoared: false, collateralFactorMantissa: 0}); tokenAddressToMToken[address(mToken.underlying())] = mToken; _addMarketInternal(address(mToken)); emit MarketListed(mToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address mToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != MToken(mToken), "market already added"); } allMarkets.push(MToken(mToken)); } /** * @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param mTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = mTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(mTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(mTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(MToken mToken, bool state) public returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(mToken)] = state; emit ActionPausedMToken(mToken, "Mint", state); return state; } function _setBorrowPaused(MToken mToken, bool state) public returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(mToken)] = state; emit ActionPausedMToken(mToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == moartrollerImplementation; } /*** MOAR Distribution ***/ /** * @notice Set MOAR speed for a single market * @param mToken The market whose MOAR speed to update * @param moarSpeed New MOAR speed for market */ function setMoarSpeedInternal(MToken mToken, uint moarSpeed) internal { uint currentMoarSpeed = moarSpeeds[address(mToken)]; if (currentMoarSpeed != 0) { // note that MOAR speed could be set to 0 to halt liquidity rewards for a market Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()}); updateMoarSupplyIndex(address(mToken)); updateMoarBorrowIndex(address(mToken), borrowIndex); } else if (moarSpeed != 0) { // Add the MOAR market Market storage market = markets[address(mToken)]; require(market.isListed == true, "MOAR market is not listed"); if (moarSupplyState[address(mToken)].index == 0 && moarSupplyState[address(mToken)].block == 0) { moarSupplyState[address(mToken)] = MoarMarketState({ index: moarInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (moarBorrowState[address(mToken)].index == 0 && moarBorrowState[address(mToken)].block == 0) { moarBorrowState[address(mToken)] = MoarMarketState({ index: moarInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } if (currentMoarSpeed != moarSpeed) { moarSpeeds[address(mToken)] = moarSpeed; emit MoarSpeedUpdated(mToken, moarSpeed); } } /** * @notice Accrue MOAR to the market by updating the supply index * @param mToken The market whose supply index to update */ function updateMoarSupplyIndex(address mToken) internal { MoarMarketState storage supplyState = moarSupplyState[mToken]; uint supplySpeed = moarSpeeds[mToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = MToken(mToken).totalSupply(); uint moarAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(moarAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); moarSupplyState[mToken] = MoarMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue MOAR to the market by updating the borrow index * @param mToken The market whose borrow index to update */ function updateMoarBorrowIndex(address mToken, Exp memory marketBorrowIndex) internal { MoarMarketState storage borrowState = moarBorrowState[mToken]; uint borrowSpeed = moarSpeeds[mToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(MToken(mToken).totalBorrows(), marketBorrowIndex); uint moarAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(moarAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); moarBorrowState[mToken] = MoarMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate MOAR accrued by a supplier and possibly transfer it to them * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute MOAR to */ function distributeSupplierMoar(address mToken, address supplier) internal { MoarMarketState storage supplyState = moarSupplyState[mToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: moarSupplierIndex[mToken][supplier]}); moarSupplierIndex[mToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = moarInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = MToken(mToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(moarAccrued[supplier], supplierDelta); moarAccrued[supplier] = supplierAccrued; emit DistributedSupplierMoar(MToken(mToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate MOAR accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOAR to */ function distributeBorrowerMoar(address mToken, address borrower, Exp memory marketBorrowIndex) internal { MoarMarketState storage borrowState = moarBorrowState[mToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: moarBorrowerIndex[mToken][borrower]}); moarBorrowerIndex[mToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(MToken(mToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(moarAccrued[borrower], borrowerDelta); moarAccrued[borrower] = borrowerAccrued; emit DistributedBorrowerMoar(MToken(mToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Calculate additional accrued MOAR for a contributor since last accrual * @param contributor The address to calculate contributor rewards for */ function updateContributorRewards(address contributor) public { uint moarSpeed = moarContributorSpeeds[contributor]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]); if (deltaBlocks > 0 && moarSpeed > 0) { uint newAccrued = mul_(deltaBlocks, moarSpeed); uint contributorAccrued = add_(moarAccrued[contributor], newAccrued); moarAccrued[contributor] = contributorAccrued; lastContributorBlock[contributor] = blockNumber; } } /** * @notice Claim all the MOAR accrued by holder in all markets * @param holder The address to claim MOAR for */ function claimMoarReward(address holder) public { return claimMoar(holder, allMarkets); } /** * @notice Claim all the MOAR accrued by holder in the specified markets * @param holder The address to claim MOAR for * @param mTokens The list of markets to claim MOAR in */ function claimMoar(address holder, MToken[] memory mTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimMoar(holders, mTokens, true, true); } /** * @notice Claim all MOAR accrued by the holders * @param holders The addresses to claim MOAR for * @param mTokens The list of markets to claim MOAR in * @param borrowers Whether or not to claim MOAR earned by borrowing * @param suppliers Whether or not to claim MOAR earned by supplying */ function claimMoar(address[] memory holders, MToken[] memory mTokens, bool borrowers, bool suppliers) public { require(rewardClaimEnabled, "reward claim is disabled"); for (uint i = 0; i < mTokens.length; i++) { MToken mToken = mTokens[i]; require(markets[address(mToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()}); updateMoarBorrowIndex(address(mToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerMoar(address(mToken), holders[j], borrowIndex); moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]); } } if (suppliers == true) { updateMoarSupplyIndex(address(mToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierMoar(address(mToken), holders[j]); moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]); } } } } /** * @notice Transfer MOAR to the user * @dev Note: If there is not enough MOAR, we do not perform the transfer all. * @param user The address of the user to transfer MOAR to * @param amount The amount of MOAR to (possibly) transfer * @return The amount of MOAR which was NOT transferred to the user */ function grantMoarInternal(address user, uint amount) internal returns (uint) { EIP20Interface moar = EIP20Interface(getMoarAddress()); uint moarRemaining = moar.balanceOf(address(this)); if (amount > 0 && amount <= moarRemaining) { moar.approve(mProxy, amount); MProxyInterface(mProxy).proxyClaimReward(getMoarAddress(), user, amount); return 0; } return amount; } /*** MOAR Distribution Admin ***/ /** * @notice Transfer MOAR to the recipient * @dev Note: If there is not enough MOAR, we do not perform the transfer all. * @param recipient The address of the recipient to transfer MOAR to * @param amount The amount of MOAR to (possibly) transfer */ function _grantMoar(address recipient, uint amount) public { require(adminOrInitializing(), "only admin can grant MOAR"); uint amountLeft = grantMoarInternal(recipient, amount); require(amountLeft == 0, "insufficient MOAR for grant"); emit MoarGranted(recipient, amount); } /** * @notice Set MOAR speed for a single market * @param mToken The market whose MOAR speed to update * @param moarSpeed New MOAR speed for market */ function _setMoarSpeed(MToken mToken, uint moarSpeed) public { require(adminOrInitializing(), "only admin can set MOAR speed"); setMoarSpeedInternal(mToken, moarSpeed); } /** * @notice Set MOAR speed for a single contributor * @param contributor The contributor whose MOAR speed to update * @param moarSpeed New MOAR speed for contributor */ function _setContributorMoarSpeed(address contributor, uint moarSpeed) public { require(adminOrInitializing(), "only admin can set MOAR speed"); // note that MOAR speed could be set to 0 to halt liquidity rewards for a contributor updateContributorRewards(contributor); if (moarSpeed == 0) { // release storage delete lastContributorBlock[contributor]; } else { lastContributorBlock[contributor] = getBlockNumber(); } moarContributorSpeeds[contributor] = moarSpeed; emit ContributorMoarSpeedUpdated(contributor, moarSpeed); } /** * @notice Set liquidity math model implementation * @param mathModel the math model implementation */ function _setLiquidityMathModel(LiquidityMathModelInterface mathModel) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); LiquidityMathModelInterface oldLiquidityMathModel = liquidityMathModel; liquidityMathModel = mathModel; emit NewLiquidityMathModel(address(oldLiquidityMathModel), address(liquidityMathModel)); } /** * @notice Set liquidation model implementation * @param newLiquidationModel the liquidation model implementation */ function _setLiquidationModel(LiquidationModelInterface newLiquidationModel) public { require(msg.sender == admin, "only admin can set liquidation model implementation"); LiquidationModelInterface oldLiquidationModel = liquidationModel; liquidationModel = newLiquidationModel; emit NewLiquidationModel(address(oldLiquidationModel), address(liquidationModel)); } function _setMoarToken(address moarTokenAddress) public { require(msg.sender == admin, "only admin can set MOAR token address"); moarToken = moarTokenAddress; } function _setMProxy(address mProxyAddress) public { require(msg.sender == admin, "only admin can set MProxy address"); mProxy = mProxyAddress; } /** * @notice Add new privileged address * @param privilegedAddress address to add */ function _addPrivilegedAddress(address privilegedAddress) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); privilegedAddresses[privilegedAddress] = 1; } /** * @notice Remove privileged address * @param privilegedAddress address to remove */ function _removePrivilegedAddress(address privilegedAddress) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); delete privilegedAddresses[privilegedAddress]; } /** * @notice Check if address if privileged * @param privilegedAddress address to check */ function isPrivilegedAddress(address privilegedAddress) public view returns (bool) { return privilegedAddresses[privilegedAddress] == 1; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (MToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the MOAR token * @return The address of MOAR */ function getMoarAddress() public view returns (address) { return moarToken; } function getContractVersion() external override pure returns(string memory){ return "V1"; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Interfaces/PriceOracle.sol"; import "./CErc20.sol"; /** * Temporary simple price feed */ contract SimplePriceOracle is PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; mapping(address => uint) prices; event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa); function getUnderlyingPrice(MToken mToken) public override view returns (uint) { if (compareStrings(mToken.symbol(), "mDAI")) { return 1e18; } else { return prices[address(MErc20(address(mToken)).underlying())]; } } function setUnderlyingPrice(MToken mToken, uint underlyingPriceMantissa) public { address asset = address(MErc20(address(mToken)).underlying()); emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa); prices[asset] = underlyingPriceMantissa; } function setDirectPrice(address asset, uint price) public { emit PricePosted(asset, prices[asset], price, price); prices[asset] = price; } // v1 price oracle interface for use as backing of proxy function assetPrices(address asset) external view returns (uint) { return prices[asset]; } function compareStrings(string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "./Interfaces/CopMappingInterface.sol"; import "./Interfaces/Versionable.sol"; import "./Moartroller.sol"; import "./Utils/ExponentialNoError.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/AssetHelpers.sol"; import "./MToken.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Utils/SafeEIP20.sol"; /** * @title MOAR's MProtection Contract * @notice Collateral optimization ERC-721 wrapper * @author MOAR */ contract MProtection is ERC721Upgradeable, OwnableUpgradeable, ExponentialNoError, AssetHelpers, Versionable { using Counters for Counters.Counter; using EnumerableSet for EnumerableSet.UintSet; /** * @notice Event emitted when new MProtection token is minted */ event Mint(address minter, uint tokenId, uint underlyingTokenId, address asset, uint amount, uint strikePrice, uint expirationTime); /** * @notice Event emitted when MProtection token is redeemed */ event Redeem(address redeemer, uint tokenId, uint underlyingTokenId); /** * @notice Event emitted when MProtection token changes its locked value */ event LockValue(uint tokenId, uint underlyingTokenId, uint optimizationValue); /** * @notice Event emitted when maturity window parameter is changed */ event MaturityWindowUpdated(uint newMaturityWindow); Counters.Counter private _tokenIds; address private _copMappingAddress; address private _moartrollerAddress; mapping (uint256 => uint256) private _underlyingProtectionTokensMapping; mapping (uint256 => uint256) private _underlyingProtectionLockedValue; mapping (address => mapping (address => EnumerableSet.UintSet)) private _protectionCurrencyMapping; uint256 public _maturityWindow; struct ProtectionMappedData{ address pool; address underlyingAsset; uint256 amount; uint256 strike; uint256 premium; uint256 lockedValue; uint256 totalValue; uint issueTime; uint expirationTime; bool isProtectionAlive; } /** * @notice Constructor for MProtection contract * @param copMappingAddress The address of data mapper for C-OP * @param moartrollerAddress The address of the Moartroller */ function initialize(address copMappingAddress, address moartrollerAddress) public initializer { __Ownable_init(); __ERC721_init("c-uUNN OC-Protection", "c-uUNN"); _copMappingAddress = copMappingAddress; _moartrollerAddress = moartrollerAddress; _setMaturityWindow(10800); // 3 hours default } /** * @notice Returns C-OP mapping contract */ function copMapping() private view returns (CopMappingInterface){ return CopMappingInterface(_copMappingAddress); } /** * @notice Mint new MProtection token * @param underlyingTokenId Id of C-OP token that will be deposited * @return ID of minted MProtection token */ function mint(uint256 underlyingTokenId) public returns (uint256) { return mintFor(underlyingTokenId, msg.sender); } /** * @notice Mint new MProtection token for specified address * @param underlyingTokenId Id of C-OP token that will be deposited * @param receiver Address that will receive minted Mprotection token * @return ID of minted MProtection token */ function mintFor(uint256 underlyingTokenId, address receiver) public returns (uint256) { CopMappingInterface copMappingInstance = copMapping(); ERC721Upgradeable(copMappingInstance.getTokenAddress()).transferFrom(msg.sender, address(this), underlyingTokenId); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(receiver, newItemId); addUProtectionIndexes(receiver, newItemId, underlyingTokenId); emit Mint( receiver, newItemId, underlyingTokenId, copMappingInstance.getUnderlyingAsset(underlyingTokenId), copMappingInstance.getUnderlyingAmount(underlyingTokenId), copMappingInstance.getUnderlyingStrikePrice(underlyingTokenId), copMappingInstance.getUnderlyingDeadline(underlyingTokenId) ); return newItemId; } /** * @notice Redeem C-OP token * @param tokenId Id of MProtection token that will be withdrawn * @return ID of redeemed C-OP token */ function redeem(uint256 tokenId) external returns (uint256) { require(_isApprovedOrOwner(_msgSender(), tokenId), "cuUNN: caller is not owner nor approved"); uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); ERC721Upgradeable(copMapping().getTokenAddress()).transferFrom(address(this), msg.sender, underlyingTokenId); removeProtectionIndexes(tokenId); _burn(tokenId); emit Redeem(msg.sender, tokenId, underlyingTokenId); return underlyingTokenId; } /** * @notice Returns set of C-OP data * @param tokenId Id of MProtection token * @return ProtectionMappedData struct filled with C-OP data */ function getMappedProtectionData(uint256 tokenId) public view returns (ProtectionMappedData memory){ ProtectionMappedData memory data; (address pool, uint256 amount, uint256 strike, uint256 premium, uint issueTime , uint expirationTime) = getProtectionData(tokenId); data = ProtectionMappedData(pool, getUnderlyingAsset(tokenId), amount, strike, premium, getUnderlyingProtectionLockedValue(tokenId), getUnderlyingProtectionTotalValue(tokenId), issueTime, expirationTime, isProtectionAlive(tokenId)); return data; } /** * @notice Returns underlying token ID * @param tokenId Id of MProtection token */ function getUnderlyingProtectionTokenId(uint256 tokenId) public view returns (uint256){ return _underlyingProtectionTokensMapping[tokenId]; } /** * @notice Returns size of C-OPs filtered by asset address * @param owner Address of wallet holding C-OPs * @param currency Address of asset used to filter C-OPs */ function getUserUnderlyingProtectionTokenIdByCurrencySize(address owner, address currency) public view returns (uint256){ return _protectionCurrencyMapping[owner][currency].length(); } /** * @notice Returns list of C-OP IDs filtered by asset address * @param owner Address of wallet holding C-OPs * @param currency Address of asset used to filter C-OPs */ function getUserUnderlyingProtectionTokenIdByCurrency(address owner, address currency, uint256 index) public view returns (uint256){ return _protectionCurrencyMapping[owner][currency].at(index); } /** * @notice Checks if address is owner of MProtection * @param owner Address of potential owner to check * @param tokenId ID of MProtection to check */ function isUserProtection(address owner, uint256 tokenId) public view returns(bool) { if(Moartroller(_moartrollerAddress).isPrivilegedAddress(msg.sender)){ return true; } return owner == ownerOf(tokenId); } /** * @notice Checks if MProtection is stil alive * @param tokenId ID of MProtection to check */ function isProtectionAlive(uint256 tokenId) public view returns(bool) { uint256 deadline = getUnderlyingDeadline(tokenId); return (deadline - _maturityWindow) > now; } /** * @notice Creates appropriate indexes for C-OP * @param owner C-OP owner address * @param tokenId ID of MProtection * @param underlyingTokenId ID of C-OP */ function addUProtectionIndexes(address owner, uint256 tokenId, uint256 underlyingTokenId) private{ address currency = copMapping().getUnderlyingAsset(underlyingTokenId); _underlyingProtectionTokensMapping[tokenId] = underlyingTokenId; _protectionCurrencyMapping[owner][currency].add(tokenId); } /** * @notice Remove indexes for C-OP * @param tokenId ID of MProtection */ function removeProtectionIndexes(uint256 tokenId) private{ address owner = ownerOf(tokenId); address currency = getUnderlyingAsset(tokenId); _underlyingProtectionTokensMapping[tokenId] = 0; _protectionCurrencyMapping[owner][currency].remove(tokenId); } /** * @notice Returns C-OP total value * @param tokenId ID of MProtection */ function getUnderlyingProtectionTotalValue(uint256 tokenId) public view returns(uint256){ address underlyingAsset = getUnderlyingAsset(tokenId); uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset); return div_( mul_( getUnderlyingStrikePrice(tokenId), getUnderlyingAmount(tokenId) ), assetDecimalsMantissa ); } /** * @notice Returns C-OP locked value * @param tokenId ID of MProtection */ function getUnderlyingProtectionLockedValue(uint256 tokenId) public view returns(uint256){ return _underlyingProtectionLockedValue[tokenId]; } /** * @notice get the amount of underlying asset that is locked * @param tokenId CProtection tokenId * @return amount locked */ function getUnderlyingProtectionLockedAmount(uint256 tokenId) public view returns(uint256){ address underlyingAsset = getUnderlyingAsset(tokenId); uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset); // calculates total protection value uint256 protectionValue = div_( mul_( getUnderlyingAmount(tokenId), getUnderlyingStrikePrice(tokenId) ), assetDecimalsMantissa ); // return value is lockedValue / totalValue * amount return div_( mul_( getUnderlyingAmount(tokenId), div_( mul_( _underlyingProtectionLockedValue[tokenId], 1e18 ), protectionValue ) ), 1e18 ); } /** * @notice Locks the given protection value as collateral optimization * @param tokenId The MProtection token id * @param value The value in stablecoin of protection to be locked as collateral optimization. 0 = max available optimization * @return locked protection value * TODO: convert semantic errors to standarized error codes */ function lockProtectionValue(uint256 tokenId, uint value) external returns(uint) { //check if the protection belongs to the caller require(isUserProtection(msg.sender, tokenId), "ERROR: CALLER IS NOT THE OWNER OF PROTECTION"); address currency = getUnderlyingAsset(tokenId); Moartroller moartroller = Moartroller(_moartrollerAddress); MToken mToken = moartroller.tokenAddressToMToken(currency); require(moartroller.oracle().getUnderlyingPrice(mToken) <= getUnderlyingStrikePrice(tokenId), "ERROR: C-OP STRIKE PRICE IS LOWER THAN ASSET SPOT PRICE"); uint protectionTotalValue = getUnderlyingProtectionTotalValue(tokenId); uint maxOptimizableValue = moartroller.getMaxOptimizableValue(mToken, ownerOf(tokenId)); // add protection locked value if any uint protectionLockedValue = getUnderlyingProtectionLockedValue(tokenId); if ( protectionLockedValue > 0) { maxOptimizableValue = add_(maxOptimizableValue, protectionLockedValue); } uint valueToLock; if (value != 0) { // check if lock value is at most max optimizable value require(value <= maxOptimizableValue, "ERROR: VALUE TO BE LOCKED EXCEEDS ALLOWED OPTIMIZATION VALUE"); // check if lock value is at most protection total value require( value <= protectionTotalValue, "ERROR: VALUE TO BE LOCKED EXCEEDS PROTECTION TOTAL VALUE"); valueToLock = value; } else { // if we want to lock maximum protection value let's lock the value that is at most max optimizable value if (protectionTotalValue > maxOptimizableValue) { valueToLock = maxOptimizableValue; } else { valueToLock = protectionTotalValue; } } _underlyingProtectionLockedValue[tokenId] = valueToLock; emit LockValue(tokenId, getUnderlyingProtectionTokenId(tokenId), valueToLock); return valueToLock; } function _setCopMapping(address newMapping) public onlyOwner { _copMappingAddress = newMapping; } function _setMoartroller(address newMoartroller) public onlyOwner { _moartrollerAddress = newMoartroller; } function _setMaturityWindow(uint256 maturityWindow) public onlyOwner { emit MaturityWindowUpdated(maturityWindow); _maturityWindow = maturityWindow; } // MAPPINGS function getProtectionData(uint256 tokenId) public view returns (address, uint256, uint256, uint256, uint, uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getProtectionData(underlyingTokenId); } function getUnderlyingAsset(uint256 tokenId) public view returns (address){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingAsset(underlyingTokenId); } function getUnderlyingAmount(uint256 tokenId) public view returns (uint256){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingAmount(underlyingTokenId); } function getUnderlyingStrikePrice(uint256 tokenId) public view returns (uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingStrikePrice(underlyingTokenId); } function getUnderlyingDeadline(uint256 tokenId) public view returns (uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingDeadline(underlyingTokenId); } function getContractVersion() external override pure returns(string memory){ return "V1"; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; interface PriceOracle { /** * @notice Get the underlying price of a mToken asset * @param mToken The mToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(MToken mToken) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance The balance */ function balanceOf(address owner) external view returns (uint256); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return success Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; abstract contract MTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @dev EIP-20 token name for this token */ string public name; /** * @dev EIP-20 token symbol for this token */ string public symbol; /** * @dev EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Underlying asset for this MToken */ address public underlying; /** * @dev Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal borrowRateMaxMantissa; /** * @dev Maximum fraction of interest that can be set aside for reserves */ uint internal reserveFactorMaxMantissa; /** * @dev Administrator for this contract */ address payable public admin; /** * @dev Pending administrator for this contract */ address payable public pendingAdmin; /** * @dev Contract which oversees inter-mToken operations */ Moartroller public moartroller; /** * @dev Model which tells what the current interest rate should be */ AbstractInterestRateModel public interestRateModel; /** * @dev Initial exchange rate used when minting the first MTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @dev Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @dev Fraction of reserves currently set aside for other usage */ uint public reserveSplitFactorMantissa; /** * @dev Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @dev Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @dev Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @dev Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @dev Total number of tokens in circulation */ uint public totalSupply; /** * @dev The Maximum Protection Moarosition (MPC) factor for collateral optimisation, default: 50% = 5000 */ uint public maxProtectionComposition; /** * @dev The Maximum Protection Moarosition (MPC) mantissa, default: 1e5 */ uint public maxProtectionCompositionMantissa; /** * @dev Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @dev Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; struct ProtectionUsage { uint256 protectionValueUsed; } /** * @dev Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; mapping (uint256 => ProtectionUsage) protectionsUsed; } struct AccrueInterestTempStorage{ uint interestAccumulated; uint reservesAdded; uint splitedReserves_1; uint splitedReserves_2; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; } /** * @dev Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) public accountBorrows; } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./EIP20Interface.sol"; interface MTokenInterface { /*** User contract ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom(address src, address dst, uint256 amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function getCash() external view returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); function getUnderlying() external view returns(address); function sweepToken(EIP20Interface token) external; /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; interface MProxyInterface { function proxyClaimReward(address asset, address recipient, uint amount) external; function proxySplitReserves(address asset, uint amount) external; } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Interfaces/InterestRateModelInterface.sol"; abstract contract AbstractInterestRateModel is InterestRateModelInterface { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @title Careful Math * @author MOAR * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; import "../Utils/ExponentialNoError.sol"; interface MoartrollerInterface { /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `mTokenBalance` is the number of mTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint mTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; ExponentialNoError.Exp collateralFactor; ExponentialNoError.Exp exchangeRate; ExponentialNoError.Exp oraclePrice; ExponentialNoError.Exp tokensToDenom; } /*** Assets You Are In ***/ function enterMarkets(address[] calldata mTokens) external returns (uint[] memory); function exitMarket(address mToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint); function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint); function repayBorrowAllowed( address mToken, address payer, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowAllowed( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function seizeAllowed( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint); /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeUserTokens( address mTokenBorrowed, address mTokenCollateral, uint repayAmount, address account) external view returns (uint, uint); function getUserLockedAmount(MToken asset, address account) external view returns(uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; interface Versionable { function getContractVersion() external pure returns (string memory); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./MToken.sol"; import "./Interfaces/PriceOracle.sol"; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./Interfaces/LiquidationModelInterface.sol"; import "./MProtection.sol"; abstract contract UnitrollerAdminStorage { /** * @dev Administrator for this contract */ address public admin; /** * @dev Pending administrator for this contract */ address public pendingAdmin; /** * @dev Active brains of Unitroller */ address public moartrollerImplementation; /** * @dev Pending brains of Unitroller */ address public pendingMoartrollerImplementation; } contract MoartrollerV1Storage is UnitrollerAdminStorage { /** * @dev Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @dev Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @dev Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @dev Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @dev Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => MToken[]) public accountAssets; } contract MoartrollerV2Storage is MoartrollerV1Storage { struct Market { // Whether or not this market is listed bool isListed; // Multiplier representing the most one can borrow against their collateral in this market. // For instance, 0.9 to allow borrowing 90% of collateral value. // Must be between 0 and 1, and stored as a mantissa. uint collateralFactorMantissa; // Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; // Whether or not this market receives MOAR bool isMoared; } /** * @dev Official mapping of mTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @dev The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract MoartrollerV3Storage is MoartrollerV2Storage { struct MoarMarketState { // The market's last updated moarBorrowIndex or moarSupplyIndex uint224 index; // The block number the index was last updated at uint32 block; } /// @dev A list of all markets MToken[] public allMarkets; /// @dev The rate at which the flywheel distributes MOAR, per block uint public moarRate; /// @dev The portion of moarRate that each market currently receives mapping(address => uint) public moarSpeeds; /// @dev The MOAR market supply state for each market mapping(address => MoarMarketState) public moarSupplyState; /// @dev The MOAR market borrow state for each market mapping(address => MoarMarketState) public moarBorrowState; /// @dev The MOAR borrow index for each market for each supplier as of the last time they accrued MOAR mapping(address => mapping(address => uint)) public moarSupplierIndex; /// @dev The MOAR borrow index for each market for each borrower as of the last time they accrued MOAR mapping(address => mapping(address => uint)) public moarBorrowerIndex; /// @dev The MOAR accrued but not yet transferred to each user mapping(address => uint) public moarAccrued; } contract MoartrollerV4Storage is MoartrollerV3Storage { // @dev The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @dev Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } contract MoartrollerV5Storage is MoartrollerV4Storage { /// @dev The portion of MOAR that each contributor receives per block mapping(address => uint) public moarContributorSpeeds; /// @dev Last block at which a contributor's MOAR rewards have been allocated mapping(address => uint) public lastContributorBlock; } contract MoartrollerV6Storage is MoartrollerV5Storage { /** * @dev Moar token address */ address public moarToken; /** * @dev MProxy address */ address public mProxy; /** * @dev CProtection contract which can be used for collateral optimisation */ MProtection public cprotection; /** * @dev Mapping for basic token address to mToken */ mapping(address => MToken) public tokenAddressToMToken; /** * @dev Math model for liquidity calculation */ LiquidityMathModelInterface public liquidityMathModel; /** * @dev Liquidation model for liquidation related functions */ LiquidationModelInterface public liquidationModel; /** * @dev List of addresses with privileged access */ mapping(address => uint) public privilegedAddresses; /** * @dev Determines if reward claim feature is enabled */ bool public rewardClaimEnabled; } // Copyright (c) 2020 The UNION Protocol Foundation // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // import "hardhat/console.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /** * @title UNION Protocol Governance Token * @dev Implementation of the basic standard token. */ contract UnionGovernanceToken is AccessControl, IERC20 { using Address for address; using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; /** * @notice Struct for marking number of votes from a given block * @member from * @member votes */ struct VotingCheckpoint { uint256 from; uint256 votes; } /** * @notice Struct for locked tokens * @member amount * @member releaseTime * @member votable */ struct LockedTokens{ uint amount; uint releaseTime; bool votable; } /** * @notice Struct for EIP712 Domain * @member name * @member version * @member chainId * @member verifyingContract * @member salt */ struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; bytes32 salt; } /** * @notice Struct for EIP712 VotingDelegate call * @member owner * @member delegate * @member nonce * @member expirationTime */ struct VotingDelegate { address owner; address delegate; uint256 nonce; uint256 expirationTime; } /** * @notice Struct for EIP712 Permit call * @member owner * @member spender * @member value * @member nonce * @member deadline */ struct Permit { address owner; address spender; uint256 value; uint256 nonce; uint256 deadline; } /** * @notice Vote Delegation Events */ event VotingDelegateChanged(address indexed _owner, address indexed _fromDelegate, address indexed _toDelegate); event VotingDelegateRemoved(address indexed _owner); /** * @notice Vote Balance Events * Emmitted when a delegate account's vote balance changes at the time of a written checkpoint */ event VoteBalanceChanged(address indexed _account, uint256 _oldBalance, uint256 _newBalance); /** * @notice Transfer/Allocator Events */ event TransferStatusChanged(bool _newTransferStatus); /** * @notice Reversion Events */ event ReversionStatusChanged(bool _newReversionSetting); /** * @notice EIP-20 Approval event */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @notice EIP-20 Transfer event */ event Transfer(address indexed _from, address indexed _to, uint256 _value); event Burn(address indexed _from, uint256 _value); event AddressPermitted(address indexed _account); event AddressRestricted(address indexed _account); /** * @dev AccessControl recognized roles */ bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); bytes32 public constant ROLE_ALLOCATE = keccak256("ROLE_ALLOCATE"); bytes32 public constant ROLE_GOVERN = keccak256("ROLE_GOVERN"); bytes32 public constant ROLE_MINT = keccak256("ROLE_MINT"); bytes32 public constant ROLE_LOCK = keccak256("ROLE_LOCK"); bytes32 public constant ROLE_TRUSTED = keccak256("ROLE_TRUSTED"); bytes32 public constant ROLE_TEST = keccak256("ROLE_TEST"); bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); bytes32 public constant DELEGATE_TYPEHASH = keccak256( "DelegateVote(address owner,address delegate,uint256 nonce,uint256 expirationTime)" ); //keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; address private constant BURN_ADDRESS = address(0); address public UPGT_CONTRACT_ADDRESS; /** * @dev hashes to support EIP-712 signing and validating, EIP712DOMAIN_SEPARATOR is set at time of contract instantiation and token minting. */ bytes32 public immutable EIP712DOMAIN_SEPARATOR; /** * @dev EIP-20 token name */ string public name = "UNION Protocol Governance Token"; /** * @dev EIP-20 token symbol */ string public symbol = "UNN"; /** * @dev EIP-20 token decimals */ uint8 public decimals = 18; /** * @dev Contract version */ string public constant version = '0.0.1'; /** * @dev Initial amount of tokens */ uint256 private uint256_initialSupply = 100000000000 * 10**18; /** * @dev Total amount of tokens */ uint256 private uint256_totalSupply; /** * @dev Chain id */ uint256 private uint256_chain_id; /** * @dev general transfer restricted as function of public sale not complete */ bool private b_canTransfer = false; /** * @dev private variable that determines if failed EIP-20 functions revert() or return false. Reversion short-circuits the return from these functions. */ bool private b_revert = false; //false allows false return values /** * @dev Locked destinations list */ mapping(address => bool) private m_lockedDestinations; /** * @dev EIP-20 allowance and balance maps */ mapping(address => mapping(address => uint256)) private m_allowances; mapping(address => uint256) private m_balances; mapping(address => LockedTokens[]) private m_lockedBalances; /** * @dev nonces used by accounts to this contract for signing and validating signatures under EIP-712 */ mapping(address => uint256) private m_nonces; /** * @dev delegated account may for off-line vote delegation */ mapping(address => address) private m_delegatedAccounts; /** * @dev delegated account inverse map is needed to live calculate voting power */ mapping(address => EnumerableSet.AddressSet) private m_delegatedAccountsInverseMap; /** * @dev indexed mapping of vote checkpoints for each account */ mapping(address => mapping(uint256 => VotingCheckpoint)) private m_votingCheckpoints; /** * @dev mapping of account addrresses to voting checkpoints */ mapping(address => uint256) private m_accountVotingCheckpoints; /** * @dev Contructor for the token * @param _owner address of token contract owner * @param _initialSupply of tokens generated by this contract * Sets Transfer the total suppply to the owner. * Sets default admin role to the owner. * Sets ROLE_ALLOCATE to the owner. * Sets ROLE_GOVERN to the owner. * Sets ROLE_MINT to the owner. * Sets EIP 712 Domain Separator. */ constructor(address _owner, uint256 _initialSupply) public { //set internal contract references UPGT_CONTRACT_ADDRESS = address(this); //setup roles using AccessControl _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(ROLE_ADMIN, _owner); _setupRole(ROLE_ADMIN, _msgSender()); _setupRole(ROLE_ALLOCATE, _owner); _setupRole(ROLE_ALLOCATE, _msgSender()); _setupRole(ROLE_TRUSTED, _owner); _setupRole(ROLE_TRUSTED, _msgSender()); _setupRole(ROLE_GOVERN, _owner); _setupRole(ROLE_MINT, _owner); _setupRole(ROLE_LOCK, _owner); _setupRole(ROLE_TEST, _owner); m_balances[_owner] = _initialSupply; uint256_totalSupply = _initialSupply; b_canTransfer = false; uint256_chain_id = _getChainId(); EIP712DOMAIN_SEPARATOR = _hash(EIP712Domain({ name : name, version : version, chainId : uint256_chain_id, verifyingContract : address(this), salt : keccak256(abi.encodePacked(name)) } )); emit Transfer(BURN_ADDRESS, _owner, uint256_totalSupply); } /** * @dev Sets transfer status to lock token transfer * @param _canTransfer value can be true or false. * disables transfer when set to false and enables transfer when true * Only a member of ADMIN role can call to change transfer status */ function setCanTransfer(bool _canTransfer) public { if(hasRole(ROLE_ADMIN, _msgSender())){ b_canTransfer = _canTransfer; emit TransferStatusChanged(_canTransfer); } } /** * @dev Gets status of token transfer lock * @return true or false status of whether the token can be transfered */ function getCanTransfer() public view returns (bool) { return b_canTransfer; } /** * @dev Sets transfer reversion status to either return false or throw on error * @param _reversion value can be true or false. * disables return of false values for transfer failures when set to false and enables transfer-related exceptions when true * Only a member of ADMIN role can call to change transfer reversion status */ function setReversion(bool _reversion) public { if(hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TEST, _msgSender()) ) { b_revert = _reversion; emit ReversionStatusChanged(_reversion); } } /** * @dev Gets status of token transfer reversion * @return true or false status of whether the token transfer failures return false or are reverted */ function getReversion() public view returns (bool) { return b_revert; } /** * @dev retrieve current chain id * @return chain id */ function getChainId() public pure returns (uint256) { return _getChainId(); } /** * @dev Retrieve current chain id * @return chain id */ function _getChainId() internal pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * @dev Retrieve total supply of tokens * @return uint256 total supply of tokens */ function totalSupply() public view override returns (uint256) { return uint256_totalSupply; } /** * Balance related functions */ /** * @dev Retrieve balance of a specified account * @param _account address of account holding balance * @return uint256 balance of the specified account address */ function balanceOf(address _account) public view override returns (uint256) { return m_balances[_account].add(_calculateReleasedBalance(_account)); } /** * @dev Retrieve locked balance of a specified account * @param _account address of account holding locked balance * @return uint256 locked balance of the specified account address */ function lockedBalanceOf(address _account) public view returns (uint256) { return _calculateLockedBalance(_account); } /** * @dev Retrieve lenght of locked balance array for specific address * @param _account address of account holding locked balance * @return uint256 locked balance array lenght */ function getLockedTokensListSize(address _account) public view returns (uint256){ require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions"); return m_lockedBalances[_account].length; } /** * @dev Retrieve locked tokens struct from locked balance array for specific address * @param _account address of account holding locked tokens * @param _index index in array with locked tokens position * @return amount of locked tokens * @return releaseTime descibes time when tokens will be unlocked * @return votable flag is describing votability of tokens */ function getLockedTokens(address _account, uint256 _index) public view returns (uint256 amount, uint256 releaseTime, bool votable){ require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions"); require(_index < m_lockedBalances[_account].length, "UPGT_ERROR: LockedTokens position doesn't exist on given index"); LockedTokens storage lockedTokens = m_lockedBalances[_account][_index]; return (lockedTokens.amount, lockedTokens.releaseTime, lockedTokens.votable); } /** * @dev Calculates locked balance of a specified account * @param _account address of account holding locked balance * @return uint256 locked balance of the specified account address */ function _calculateLockedBalance(address _account) private view returns (uint256) { uint256 lockedBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime > block.timestamp){ lockedBalance = lockedBalance.add(m_lockedBalances[_account][i].amount); } } return lockedBalance; } /** * @dev Calculates released balance of a specified account * @param _account address of account holding released balance * @return uint256 released balance of the specified account address */ function _calculateReleasedBalance(address _account) private view returns (uint256) { uint256 releasedBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){ releasedBalance = releasedBalance.add(m_lockedBalances[_account][i].amount); } } return releasedBalance; } /** * @dev Calculates locked votable balance of a specified account * @param _account address of account holding locked votable balance * @return uint256 locked votable balance of the specified account address */ function _calculateLockedVotableBalance(address _account) private view returns (uint256) { uint256 lockedVotableBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].votable == true){ lockedVotableBalance = lockedVotableBalance.add(m_lockedBalances[_account][i].amount); } } return lockedVotableBalance; } /** * @dev Moves released balance to normal balance for a specified account * @param _account address of account holding released balance */ function _moveReleasedBalance(address _account) internal virtual{ uint256 releasedToMove = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){ releasedToMove = releasedToMove.add(m_lockedBalances[_account][i].amount); m_lockedBalances[_account][i] = m_lockedBalances[_account][m_lockedBalances[_account].length - 1]; m_lockedBalances[_account].pop(); } } m_balances[_account] = m_balances[_account].add(releasedToMove); } /** * Allowance related functinons */ /** * @dev Retrieve the spending allowance for a token holder by a specified account * @param _owner Token account holder * @param _spender Account given allowance * @return uint256 allowance value */ function allowance(address _owner, address _spender) public override virtual view returns (uint256) { return m_allowances[_owner][_spender]; } /** * @dev Message sender approval to spend for a specified amount * @param _spender address of party approved to spend * @param _value amount of the approval * @return boolean success status * public wrapper for _approve, _owner is msg.sender */ function approve(address _spender, uint256 _value) public override returns (bool) { bool success = _approveUNN(_msgSender(), _spender, _value); if(!success && b_revert){ revert("UPGT_ERROR: APPROVE ERROR"); } return success; } /** * @dev Token owner approval of amount for specified spender * @param _owner address of party that owns the tokens being granted approval for spending * @param _spender address of party that is granted approval for spending * @param _value amount approved for spending * @return boolean approval status * if _spender allownace for a given _owner is greater than 0, * increaseAllowance/decreaseAllowance should be used to prevent a race condition whereby the spender is able to spend the total value of both the old and new allowance. _spender cannot be burn or this governance token contract address. Addresses github.com/ethereum/EIPs/issues738 */ function _approveUNN(address _owner, address _spender, uint256 _value) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && (m_allowances[_owner][_spender] == 0 || _value == 0) ){ m_allowances[_owner][_spender] = _value; emit Approval(_owner, _spender, _value); retval = true; } return retval; } /** * @dev Increase spender allowance by specified incremental value * @param _spender address of party that is granted approval for spending * @param _addedValue specified incremental increase * @return boolean increaseAllowance status * public wrapper for _increaseAllowance, _owner restricted to msg.sender */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { bool success = _increaseAllowanceUNN(_msgSender(), _spender, _addedValue); if(!success && b_revert){ revert("UPGT_ERROR: INCREASE ALLOWANCE ERROR"); } return success; } /** * @dev Allow owner to increase spender allowance by specified incremental value * @param _owner address of the token owner * @param _spender address of the token spender * @param _addedValue specified incremental increase * @return boolean return value status * increase the number of tokens that an _owner provides as allowance to a _spender-- does not requrire the number of tokens allowed to be set first to 0. _spender cannot be either burn or this goverance token contract address. */ function _increaseAllowanceUNN(address _owner, address _spender, uint256 _addedValue) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && _addedValue > 0 ){ m_allowances[_owner][_spender] = m_allowances[_owner][_spender].add(_addedValue); retval = true; emit Approval(_owner, _spender, m_allowances[_owner][_spender]); } return retval; } /** * @dev Decrease spender allowance by specified incremental value * @param _spender address of party that is granted approval for spending * @param _subtractedValue specified incremental decrease * @return boolean success status * public wrapper for _decreaseAllowance, _owner restricted to msg.sender */ //public wrapper for _decreaseAllowance, _owner restricted to msg.sender function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { bool success = _decreaseAllowanceUNN(_msgSender(), _spender, _subtractedValue); if(!success && b_revert){ revert("UPGT_ERROR: DECREASE ALLOWANCE ERROR"); } return success; } /** * @dev Allow owner to decrease spender allowance by specified incremental value * @param _owner address of the token owner * @param _spender address of the token spender * @param _subtractedValue specified incremental decrease * @return boolean return value status * decrease the number of tokens than an _owner provdes as allowance to a _spender. A _spender cannot have a negative allowance. Does not require existing allowance to be set first to 0. _spender cannot be burn or this governance token contract address. */ function _decreaseAllowanceUNN(address _owner, address _spender, uint256 _subtractedValue) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && _subtractedValue > 0 && m_allowances[_owner][_spender] >= _subtractedValue ){ m_allowances[_owner][_spender] = m_allowances[_owner][_spender].sub(_subtractedValue); retval = true; emit Approval(_owner, _spender, m_allowances[_owner][_spender]); } return retval; } /** * LockedDestination related functions */ /** * @dev Adds address as a designated destination for tokens when locked for allocation only * @param _address Address of approved desitnation for movement during lock * @return success in setting address as eligible for transfer independent of token lock status */ function setAsEligibleLockedDestination(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ m_lockedDestinations[_address] = true; retVal = true; } return retVal; } /** * @dev removes desitnation as eligible for transfer * @param _address address being removed */ function removeEligibleLockedDestination(address _address) public { if(hasRole(ROLE_ADMIN, _msgSender())){ require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); delete(m_lockedDestinations[_address]); } } /** * @dev checks whether a destination is eligible as recipient of transfer independent of token lock status * @param _address address being checked * @return whether desitnation is locked */ function checkEligibleLockedDesination(address _address) public view returns (bool) { return m_lockedDestinations[_address]; } /** * @dev Adds address as a designated allocator that can move tokens when they are locked * @param _address Address receiving the role of ROLE_ALLOCATE * @return success as true or false */ function setAsAllocator(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ grantRole(ROLE_ALLOCATE, _address); retVal = true; } return retVal; } /** * @dev Removes address as a designated allocator that can move tokens when they are locked * @param _address Address being removed from the ROLE_ALLOCATE * @return success as true or false */ function removeAsAllocator(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ if(hasRole(ROLE_ALLOCATE, _address)){ revokeRole(ROLE_ALLOCATE, _address); retVal = true; } } return retVal; } /** * @dev Checks to see if an address has the role of being an allocator * @param _address Address being checked for ROLE_ALLOCATE * @return true or false whether the address has ROLE_ALLOCATE assigned */ function checkAsAllocator(address _address) public view returns (bool) { return hasRole(ROLE_ALLOCATE, _address); } /** * Transfer related functions */ /** * @dev Public wrapper for transfer function to move tokens of specified value to a given address * @param _to specified recipient * @param _value amount being transfered to recipient * @return status of transfer success */ function transfer(address _to, uint256 _value) external override returns (bool) { bool success = _transferUNN(_msgSender(), _to, _value); if(!success && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER"); } return success; } /** * @dev Transfer token for a specified address, but cannot transfer tokens to either the burn or this governance contract address. Also moves voting delegates as required. * @param _owner The address owner where transfer originates * @param _to The address to transfer to * @param _value The amount to be transferred * @return status of transfer success */ function _transferUNN(address _owner, address _to, uint256 _value) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value >= 0) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_balances[_to] = m_balances[_to].add(_value); retval = true; //need to move voting delegates with transfer of tokens retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public wrapper for transferAndLock function to move tokens of specified value to a given address and lock them for a period of time * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success * Requires ROLE_LOCK */ function transferAndLock(address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) { bool retval = false; if(hasRole(ROLE_LOCK, _msgSender())){ retval = _transferAndLock(msg.sender, _to, _value, _releaseTime, _votable); } if(!retval && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER AND LOCK"); } return retval; } /** * @dev Transfers tokens of specified value to a given address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success */ function _transferAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal virtual returns (bool){ bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value >= 0) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable)); retval = true; //need to move voting delegates with transfer of tokens // retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public wrapper for transferFrom function * @param _owner The address to transfer from * @param _spender cannot be the burn address * @param _value The amount to be transferred * @return status of transferFrom success * _spender cannot be either this goverance token contract or burn */ function transferFrom(address _owner, address _spender, uint256 _value) external override returns (bool) { bool success = _transferFromUNN(_owner, _spender, _value); if(!success && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER FROM"); } return success; } /** * @dev Transfer token for a specified address. _spender cannot be either this goverance token contract or burn * @param _owner The address to transfer from * @param _spender cannot be the burn address * @param _value The amount to be transferred * @return status of transferFrom success * _spender cannot be either this goverance token contract or burn */ function _transferFromUNN(address _owner, address _spender, uint256 _value) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_spender)) { if( _spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value > 0) && (m_allowances[_owner][_msgSender()] >= _value) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_balances[_spender] = m_balances[_spender].add(_value); m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value); retval = true; //need to move delegates that exist for this owner in line with transfer retval = retval && _moveVotingDelegates(_owner, _spender, _value); emit Transfer(_owner, _spender, _value); } } return retval; } /** * @dev Public wrapper for transferFromAndLock function to move tokens of specified value from given address to another address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success * Requires ROLE_LOCK */ function transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) { bool retval = false; if(hasRole(ROLE_LOCK, _msgSender())){ retval = _transferFromAndLock(_owner, _to, _value, _releaseTime, _votable); } if(!retval && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER FROM AND LOCK"); } return retval; } /** * @dev Transfers tokens of specified value from a given address to another address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success */ function _transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value > 0) && (m_allowances[_owner][_msgSender()] >= _value) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable)); m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value); retval = true; //need to move delegates that exist for this owner in line with transfer // retval = retval && _moveVotingDelegates(_owner, _to, _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public function to burn tokens * @param _value number of tokens to be burned * @return whether tokens were burned * Only ROLE_MINTER may burn tokens */ function burn(uint256 _value) external returns (bool) { bool success = _burn(_value); if(!success && b_revert){ revert("UPGT_ERROR: FAILED TO BURN"); } return success; } /** * @dev Private function Burn tokens * @param _value number of tokens to be burned * @return bool whether the tokens were burned * only a minter may burn tokens, meaning that tokens being burned must be previously send to a ROLE_MINTER wallet. */ function _burn(uint256 _value) internal returns (bool) { bool retval = false; if(hasRole(ROLE_MINT, _msgSender()) && (m_balances[_msgSender()] >= _value) ){ m_balances[_msgSender()] -= _value; uint256_totalSupply = uint256_totalSupply.sub(_value); retval = true; emit Burn(_msgSender(), _value); } return retval; } /** * Voting related functions */ /** * @dev Public wrapper for _calculateVotingPower function which calulates voting power * @dev voting power = balance + locked votable balance + delegations * @return uint256 voting power */ function calculateVotingPower() public view returns (uint256) { return _calculateVotingPower(_msgSender()); } /** * @dev Calulates voting power of specified address * @param _account address of token holder * @return uint256 voting power */ function _calculateVotingPower(address _account) private view returns (uint256) { uint256 votingPower = m_balances[_account].add(_calculateLockedVotableBalance(_account)); for (uint i=0; i<m_delegatedAccountsInverseMap[_account].length(); i++) { if(m_delegatedAccountsInverseMap[_account].at(i) != address(0)){ address delegatedAccount = m_delegatedAccountsInverseMap[_account].at(i); votingPower = votingPower.add(m_balances[delegatedAccount]).add(_calculateLockedVotableBalance(delegatedAccount)); } } return votingPower; } /** * @dev Moves a number of votes from a token holder to a designated representative * @param _source address of token holder * @param _destination address of voting delegate * @param _amount of voting delegation transfered to designated representative * @return bool whether move was successful * Requires ROLE_TEST */ function moveVotingDelegates( address _source, address _destination, uint256 _amount) public returns (bool) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _moveVotingDelegates(_source, _destination, _amount); } /** * @dev Moves a number of votes from a token holder to a designated representative * @param _source address of token holder * @param _destination address of voting delegate * @param _amount of voting delegation transfered to designated representative * @return bool whether move was successful */ function _moveVotingDelegates( address _source, address _destination, uint256 _amount ) internal returns (bool) { if(_source != _destination && _amount > 0) { if(_source != BURN_ADDRESS) { uint256 sourceNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_source]; uint256 sourceNumberOfVotingCheckpointsOriginal = (sourceNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][sourceNumberOfVotingCheckpoints.sub(1)].votes : 0; if(sourceNumberOfVotingCheckpointsOriginal >= _amount) { uint256 sourceNumberOfVotingCheckpointsNew = sourceNumberOfVotingCheckpointsOriginal.sub(_amount); _writeVotingCheckpoint(_source, sourceNumberOfVotingCheckpoints, sourceNumberOfVotingCheckpointsOriginal, sourceNumberOfVotingCheckpointsNew); } } if(_destination != BURN_ADDRESS) { uint256 destinationNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_destination]; uint256 destinationNumberOfVotingCheckpointsOriginal = (destinationNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][destinationNumberOfVotingCheckpoints.sub(1)].votes : 0; uint256 destinationNumberOfVotingCheckpointsNew = destinationNumberOfVotingCheckpointsOriginal.add(_amount); _writeVotingCheckpoint(_destination, destinationNumberOfVotingCheckpoints, destinationNumberOfVotingCheckpointsOriginal, destinationNumberOfVotingCheckpointsNew); } } return true; } /** * @dev Writes voting checkpoint for a given voting delegate * @param _votingDelegate exercising votes * @param _numberOfVotingCheckpoints number of voting checkpoints for current vote * @param _oldVotes previous number of votes * @param _newVotes new number of votes * Public function for writing voting checkpoint * Requires ROLE_TEST */ function writeVotingCheckpoint( address _votingDelegate, uint256 _numberOfVotingCheckpoints, uint256 _oldVotes, uint256 _newVotes) public { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); _writeVotingCheckpoint(_votingDelegate, _numberOfVotingCheckpoints, _oldVotes, _newVotes); } /** * @dev Writes voting checkpoint for a given voting delegate * @param _votingDelegate exercising votes * @param _numberOfVotingCheckpoints number of voting checkpoints for current vote * @param _oldVotes previous number of votes * @param _newVotes new number of votes * Private function for writing voting checkpoint */ function _writeVotingCheckpoint( address _votingDelegate, uint256 _numberOfVotingCheckpoints, uint256 _oldVotes, uint256 _newVotes) internal { if(_numberOfVotingCheckpoints > 0 && m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints.sub(1)].from == block.number) { m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints-1].votes = _newVotes; } else { m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints] = VotingCheckpoint(block.number, _newVotes); _numberOfVotingCheckpoints = _numberOfVotingCheckpoints.add(1); } emit VoteBalanceChanged(_votingDelegate, _oldVotes, _newVotes); } /** * @dev Calculate account votes as of a specific block * @param _account address whose votes are counted * @param _blockNumber from which votes are being counted * @return number of votes counted */ function getVoteCountAtBlock( address _account, uint256 _blockNumber) public view returns (uint256) { uint256 voteCount = 0; if(_blockNumber < block.number) { if(m_accountVotingCheckpoints[_account] != 0) { if(m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].from <= _blockNumber) { voteCount = m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].votes; } else if(m_votingCheckpoints[_account][0].from > _blockNumber) { voteCount = 0; } else { uint256 lower = 0; uint256 upper = m_accountVotingCheckpoints[_account].sub(1); while(upper > lower) { uint256 center = upper.sub((upper.sub(lower).div(2))); VotingCheckpoint memory votingCheckpoint = m_votingCheckpoints[_account][center]; if(votingCheckpoint.from == _blockNumber) { voteCount = votingCheckpoint.votes; break; } else if(votingCheckpoint.from < _blockNumber) { lower = center; } else { upper = center.sub(1); } } } } } return voteCount; } /** * @dev Vote Delegation Functions * @param _to address where message sender is assigning votes * @return success of message sender delegating vote * delegate function does not allow assignment to burn */ function delegateVote(address _to) public returns (bool) { return _delegateVote(_msgSender(), _to); } /** * @dev Delegate votes from token holder to another address * @param _from Token holder * @param _toDelegate Address that will be delegated to for purpose of voting * @return success as to whether delegation has been a success */ function _delegateVote( address _from, address _toDelegate) internal returns (bool) { bool retval = false; if(_toDelegate != BURN_ADDRESS) { address currentDelegate = m_delegatedAccounts[_from]; uint256 fromAccountBalance = m_balances[_from].add(_calculateLockedVotableBalance(_from)); address oldToDelegate = m_delegatedAccounts[_from]; m_delegatedAccounts[_from] = _toDelegate; m_delegatedAccountsInverseMap[oldToDelegate].remove(_from); if(_from != _toDelegate){ m_delegatedAccountsInverseMap[_toDelegate].add(_from); } retval = true; retval = retval && _moveVotingDelegates(currentDelegate, _toDelegate, fromAccountBalance); if(retval) { if(_from == _toDelegate){ emit VotingDelegateRemoved(_from); } else{ emit VotingDelegateChanged(_from, currentDelegate, _toDelegate); } } } return retval; } /** * @dev Revert voting delegate control to owner account * @param _account The account that has delegated its vote * @return success of reverting delegation to owner */ function _revertVotingDelegationToOwner(address _account) internal returns (bool) { return _delegateVote(_account, _account); } /** * @dev Used by an message sending account to recall its voting delegates * @return success of reverting delegation to owner */ function recallVotingDelegate() public returns (bool) { return _revertVotingDelegationToOwner(_msgSender()); } /** * @dev Retrieve the voting delegate for a specified account * @param _account The account that has delegated its vote */ function getVotingDelegate(address _account) public view returns (address) { return m_delegatedAccounts[_account]; } /** * EIP-712 related functions */ /** * @dev EIP-712 Ethereum Typed Structured Data Hashing and Signing for Allocation Permit * @param _owner address of token owner * @param _spender address of designated spender * @param _value value permitted for spend * @param _deadline expiration of signature * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter */ function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _ecv, bytes32 _ecr, bytes32 _ecs ) external returns (bool) { require(block.timestamp <= _deadline, "UPGT_ERROR: wrong timestamp"); require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", EIP712DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, m_nonces[_owner]++, _deadline)) ) ); require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user"); require(_owner != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); return _approveUNN(_owner, _spender, _value); } /** * @dev EIP-712 ETH Typed Structured Data Hashing and Signing for Delegate Vote * @param _owner address of token owner * @param _delegate address of voting delegate * @param _expiretimestamp expiration of delegation signature * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @ @return bool true or false depedening on whether vote was successfully delegated */ function delegateVoteBySignature( address _owner, address _delegate, uint256 _expiretimestamp, uint8 _ecv, bytes32 _ecr, bytes32 _ecs ) external returns (bool) { require(block.timestamp <= _expiretimestamp, "UPGT_ERROR: wrong timestamp"); require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", EIP712DOMAIN_SEPARATOR, _hash(VotingDelegate( { owner : _owner, delegate : _delegate, nonce : m_nonces[_owner]++, expirationTime : _expiretimestamp }) ) ) ); require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user"); require(_owner!= BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); return _delegateVote(_owner, _delegate); } /** * @dev Public hash EIP712Domain struct for EIP-712 * @param _eip712Domain EIP712Domain struct * @return bytes32 hash of _eip712Domain * Requires ROLE_TEST */ function hashEIP712Domain(EIP712Domain memory _eip712Domain) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_eip712Domain); } /** * @dev Hash Delegate struct for EIP-712 * @param _delegate VotingDelegate struct * @return bytes32 hash of _delegate * Requires ROLE_TEST */ function hashDelegate(VotingDelegate memory _delegate) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_delegate); } /** * @dev Public hash Permit struct for EIP-712 * @param _permit Permit struct * @return bytes32 hash of _permit * Requires ROLE_TEST */ function hashPermit(Permit memory _permit) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_permit); } /** * @param _digest signed, hashed message * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @return address of the validated signer * based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function * Requires ROLE_TEST */ function recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) public view returns (address) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _recoverSigner(_digest, _ecv, _ecr, _ecs); } /** * @dev Private hash EIP712Domain struct for EIP-712 * @param _eip712Domain EIP712Domain struct * @return bytes32 hash of _eip712Domain */ function _hash(EIP712Domain memory _eip712Domain) internal pure returns (bytes32) { return keccak256( abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(_eip712Domain.name)), keccak256(bytes(_eip712Domain.version)), _eip712Domain.chainId, _eip712Domain.verifyingContract, _eip712Domain.salt ) ); } /** * @dev Private hash Delegate struct for EIP-712 * @param _delegate VotingDelegate struct * @return bytes32 hash of _delegate */ function _hash(VotingDelegate memory _delegate) internal pure returns (bytes32) { return keccak256( abi.encode( DELEGATE_TYPEHASH, _delegate.owner, _delegate.delegate, _delegate.nonce, _delegate.expirationTime ) ); } /** * @dev Private hash Permit struct for EIP-712 * @param _permit Permit struct * @return bytes32 hash of _permit */ function _hash(Permit memory _permit) internal pure returns (bytes32) { return keccak256(abi.encode( PERMIT_TYPEHASH, _permit.owner, _permit.spender, _permit.value, _permit.nonce, _permit.deadline )); } /** * @dev Recover signer information from provided digest * @param _digest signed, hashed message * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @return address of the validated signer * based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function */ function _recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if(uint256(_ecs) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if(_ecv != 27 && _ecv != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(_digest, _ecv, _ecr, _ecs); require(signer != BURN_ADDRESS, "ECDSA: invalid signature"); return signer; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../Interfaces/EIP20Interface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeEIP20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * This is a forked version of Openzeppelin's SafeERC20 contract but supporting * EIP20Interface instead of Openzeppelin's IERC20 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeEIP20 { using SafeMath for uint256; using Address for address; function safeTransfer(EIP20Interface token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(EIP20Interface token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(EIP20Interface token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(EIP20Interface token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(EIP20Interface token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(EIP20Interface token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; import "./PriceOracle.sol"; import "./MoartrollerInterface.sol"; pragma solidity ^0.6.12; interface LiquidationModelInterface { function liquidateCalculateSeizeUserTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint); function liquidateCalculateSeizeTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint); struct LiquidateCalculateSeizeUserTokensArgumentsSet { PriceOracle oracle; MoartrollerInterface moartroller; address mTokenBorrowed; address mTokenCollateral; uint actualRepayAmount; address accountForLiquidation; uint liquidationIncentiveMantissa; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; /** * @title MOAR's InterestRateModel Interface * @author MOAR */ interface InterestRateModelInterface { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721Upgradeable.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } uint256[41] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface CopMappingInterface { function getTokenAddress() external view returns (address); function getProtectionData(uint256 underlyingTokenId) external view returns (address, uint256, uint256, uint256, uint, uint); function getUnderlyingAsset(uint256 underlyingTokenId) external view returns (address); function getUnderlyingAmount(uint256 underlyingTokenId) external view returns (uint256); function getUnderlyingStrikePrice(uint256 underlyingTokenId) external view returns (uint); function getUnderlyingDeadline(uint256 underlyingTokenId) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMapUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./MToken.sol"; import "./Interfaces/MErc20Interface.sol"; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Utils/SafeEIP20.sol"; /** * @title MOAR's MErc20 Contract * @notice MTokens which wrap an EIP-20 underlying */ contract MErc20 is MToken, MErc20Interface { using SafeEIP20 for EIP20Interface; /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param moartroller_ The address of the Moartroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function init(address underlying_, Moartroller moartroller_, AbstractInterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // MToken initialize does the bulk of the work super.init(moartroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives mTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external override returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems mTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of mTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external override returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems mTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external override returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external override returns (uint) { return borrowInternal(borrowAmount); } function borrowFor(address payable borrower, uint borrowAmount) external override returns (uint) { return borrowForInternal(borrower, borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external override returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower. * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external override returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param mTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external override returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, mTokenCollateral); return err; } /** * @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock) * @param token The address of the ERC-20 token to sweep */ function sweepToken(EIP20Interface token) override external { require(address(token) != underlying, "MErc20::sweepToken: can not sweep underlying token"); uint256 balance = token.balanceOf(address(this)); token.safeTransfer(admin, balance); } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external override returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal override view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. *` * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal override returns (uint) { EIP20Interface token = EIP20Interface(underlying); uint balanceBefore = token.balanceOf(address(this)); token.safeTransferFrom(from, address(this), amount); // Calculate the amount that was *actually* transferred uint balanceAfter = token.balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal override { EIP20Interface token = EIP20Interface(underlying); token.safeTransfer(to, amount); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; interface MErc20Interface { /*** User contract ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function borrowFor(address payable borrower, uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); }
Retrieve locked balance of a specified account _account address of account holding locked balance return uint256 locked balance of the specified account address/
function lockedBalanceOf(address _account) public view returns (uint256) { return _calculateLockedBalance(_account); }
11,818,506
pragma solidity ^0.5.16; library SafeMath { function MUL808(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV72(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB229(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD121(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD464(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED920(address previousOwner, address newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED920(address(0), _owner); } function OWNER455() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER459() { //inject NONSTANDARD NAMING require(ISOWNER595()); _; } function ISOWNER595() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP898() public ONLYOWNER459 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED920(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP989(address newOwner) public ONLYOWNER459 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP338(newOwner); } function _TRANSFEROWNERSHIP338(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED920(_owner, newOwner); _owner = newOwner; } } contract AutoRedDotDistrict is Ownable { using SafeMath for uint256; // Anyone can call the createAuction function to receive a small reward when // any of the whitelisted kitties are available to sire. uint256 public auctionCreationReward = 10000000000000000; // 0.01 ETH // Users can only call createAuction for kitties that are whitelisted by // the owner. mapping (uint256 => bool) public kittyIsWhitelisted; uint256 public numberOfWhitelistedKitties; // The owner can set startingPrice, endingPrice, and auctionDuration for // siring auctions. mapping (uint256 => uint256) public startingSiringPriceForKitty; uint256 public globalEndingSiringPrice = 0; uint256 public globalAuctionDuration = 1296000; // 15 Days (in seconds) address public kittyCoreAddress = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; address public kittySiresAddress = 0xC7af99Fe5513eB6710e6D5f44F9989dA40F27F26; // Anyone can call this function to claim the auctionCreationReward when // any of the red dot district kitties are rested and ready to sire. // The auctionCreationReward funds come from the previous successful sire // auctions, so the owner does not have to keep refilling this contract. // This function is still callable even if the contract does not have enough // for the auctionCreationReward, the caller will simply not be rewarded. function CREATEAUCTION906(uint256 _kittyId) external { //inject NONSTANDARD NAMING require(kittyIsWhitelisted[_kittyId] == true, 'kitty is not whitelisted'); KittyCore(kittyCoreAddress).CREATESIRINGAUCTION26( _kittyId, startingSiringPriceForKitty[_kittyId], globalEndingSiringPrice, globalAuctionDuration ); uint256 contractBalance = address(this).balance; if(contractBalance >= auctionCreationReward){ msg.sender.transfer(auctionCreationReward); } } function OWNERCHANGESTARTINGSIRINGPRICE514(uint256 _kittyId, uint256 _newStartingSiringPrice) external ONLYOWNER459 { //inject NONSTANDARD NAMING startingSiringPriceForKitty[_kittyId] = _newStartingSiringPrice; } function OWNERCHANGEGLOBALENDINGSIRINGPRICE671(uint256 _newGlobalEndingSiringPrice) external ONLYOWNER459 { //inject NONSTANDARD NAMING globalEndingSiringPrice = _newGlobalEndingSiringPrice; } function OWNERCHANGEGLOBALAUCTIONDURATION321(uint256 _newGlobalAuctionDuration) external ONLYOWNER459 { //inject NONSTANDARD NAMING globalAuctionDuration = _newGlobalAuctionDuration; } function OWNERCHANGEAUCTIONCREATIONREWARD955(uint256 _newAuctionCreationReward) external ONLYOWNER459 { //inject NONSTANDARD NAMING auctionCreationReward = _newAuctionCreationReward; } function OWNERCANCELSIRINGAUCTION522(uint256 _kittyId) external ONLYOWNER459 { //inject NONSTANDARD NAMING KittySires(kittySiresAddress).CANCELAUCTION283(_kittyId); } function OWNERWITHDRAWKITTY460(address _destination, uint256 _kittyId) external ONLYOWNER459 { //inject NONSTANDARD NAMING KittyCore(kittyCoreAddress).TRANSFER410(_destination, _kittyId); } function OWNERWHITELISTKITTY644(uint256 _kittyId, bool _whitelist) external ONLYOWNER459 { //inject NONSTANDARD NAMING kittyIsWhitelisted[_kittyId] = _whitelist; if(_whitelist){ numberOfWhitelistedKitties = numberOfWhitelistedKitties.ADD121(1); } else { numberOfWhitelistedKitties = numberOfWhitelistedKitties.SUB229(1); } } // This is the main withdrawal function that the owner can call to claim // earnings. It leaves numberOfWhitelistedKitties * auctionCreationReward // in the contract to incentivize future callers of the createAuction // function. function OWNERWITHDRAWALLEARNINGS662() external ONLYOWNER459 { //inject NONSTANDARD NAMING uint256 contractBalance = address(this).balance; uint256 fundsToLeaveToIncentivizeFutureCallers = auctionCreationReward.MUL808(numberOfWhitelistedKitties); if(contractBalance > fundsToLeaveToIncentivizeFutureCallers){ uint256 earnings = contractBalance.SUB229(fundsToLeaveToIncentivizeFutureCallers); msg.sender.transfer(earnings); } } // This is an emergency function that the owner can call to retrieve all // ether, including the ether that would normally be left in the contract to // incentivize future callers of the createAuction function. function EMERGENCYWITHDRAW520() external ONLYOWNER459 { //inject NONSTANDARD NAMING msg.sender.transfer(address(this).balance); } constructor() public { // Initialize starting prices for the six EN04 generation 0 kitties startingSiringPriceForKitty[848437] = 200000000000000000; // 0.2 ETH startingSiringPriceForKitty[848439] = 200000000000000000; // 0.2 ETH startingSiringPriceForKitty[848440] = 200000000000000000; // 0.2 ETH startingSiringPriceForKitty[848441] = 200000000000000000; // 0.2 ETH startingSiringPriceForKitty[848442] = 200000000000000000; // 0.2 ETH startingSiringPriceForKitty[848582] = 200000000000000000; // 0.2 ETH // Whitelist the six EN04 generation 0 kitties kittyIsWhitelisted[848437] = true; kittyIsWhitelisted[848439] = true; kittyIsWhitelisted[848440] = true; kittyIsWhitelisted[848441] = true; kittyIsWhitelisted[848442] = true; kittyIsWhitelisted[848582] = true; numberOfWhitelistedKitties = 6; // Transfer ownership to Dapper Labs original Red Dot District EOA // account on mainnet, they can change ownership to whatever address // they wish after that. TRANSFEROWNERSHIP989(0xBb1e390b77Ff99f2765e78EF1A7d069c29406bee); } function() external payable {} } contract KittyCore { function TRANSFER410(address _to, uint256 _tokenId) external; //inject NONSTANDARD NAMING function CREATESIRINGAUCTION26(uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external; //inject NONSTANDARD NAMING } contract KittySires { function CANCELAUCTION283(uint256 _tokenId) external; //inject NONSTANDARD NAMING }
inject NONSTANDARD NAMING
function TRANSFEROWNERSHIP989(address newOwner) public ONLYOWNER459 {
5,420,436
/** * The test edgeless casino contract v2 holds the players&#39;s funds and provides state channel functionality. * The casino has at no time control over the players&#39;s funds. * State channels can be updated and closed from both parties: the player and the casino. * author: Rytis Grincevicius **/ pragma solidity ^0.4.21; contract SafeMath { function safeSub(uint a, uint b) pure internal returns(uint) { assert(b <= a); return a - b; } function safeSub(int a, int b) pure internal returns(int) { if(b < 0) assert(a - b > a); else assert(a - b <= a); return a - b; } function safeAdd(uint a, uint b) pure internal returns(uint) { uint c = a + b; assert(c >= a && c >= b); return c; } function safeMul(uint a, uint b) pure internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } } contract Token { function transferFrom(address sender, address receiver, uint amount) public returns(bool success); function transfer(address receiver, uint amount) public returns(bool success); function balanceOf(address holder) public view returns(uint); } contract Owned { address public owner; modifier onlyOwner { require(msg.sender == owner); _; } function Owned() public{ owner = msg.sender; } } /** owner should be able to close the contract is nobody has been using it for at least 30 days */ contract Mortal is Owned { /** contract can be closed by the owner anytime after this timestamp if non-zero */ uint public closeAt; /** the edgeless token contract */ Token edg; function Mortal(address tokenContract) internal{ edg = Token(tokenContract); } /** * lets the owner close the contract if there are no player funds on it or if nobody has been using it for at least 30 days */ function closeContract(uint playerBalance) internal{ if(closeAt == 0) closeAt = now + 30 days; if(closeAt < now || playerBalance == 0){ edg.transfer(owner, edg.balanceOf(address(this))); selfdestruct(owner); } } /** * in case close has been called accidentally. **/ function open() onlyOwner public{ closeAt = 0; } /** * make sure the contract is not in process of being closed. **/ modifier isAlive { require(closeAt == 0); _; } /** * delays the time of closing. **/ modifier keepAlive { if(closeAt > 0) closeAt = now + 30 days; _; } } contract RequiringAuthorization is Mortal { /** indicates if an address is authorized to act in the casino&#39;s name */ mapping(address => bool) public authorized; /** tells if an address is allowed to receive funds from the bankroll **/ mapping(address => bool) public allowedReceiver; modifier onlyAuthorized { require(authorized[msg.sender]); _; } /** * Constructor. Authorize the owner. * */ function RequiringAuthorization() internal { authorized[msg.sender] = true; allowedReceiver[msg.sender] = true; } /** * authorize a address to call game functions and set configs. * @param addr the address to be authorized **/ function authorize(address addr) public onlyOwner { authorized[addr] = true; } /** * deauthorize a address to call game functions and set configs. * @param addr the address to be deauthorized **/ function deauthorize(address addr) public onlyOwner { authorized[addr] = false; } /** * allow authorized wallets to withdraw funds from the bonkroll to this address * @param receiver the receiver&#39;s address * */ function allowReceiver(address receiver) public onlyOwner { allowedReceiver[receiver] = true; } /** * disallow authorized wallets to withdraw funds from the bonkroll to this address * @param receiver the receiver&#39;s address * */ function disallowReceiver(address receiver) public onlyOwner { allowedReceiver[receiver] = false; } /** * changes the owner of the contract. revokes authorization of the old owner and authorizes the new one. * @param newOwner the address of the new owner * */ function changeOwner(address newOwner) public onlyOwner { deauthorize(owner); authorize(newOwner); disallowReceiver(owner); allowReceiver(newOwner); owner = newOwner; } } contract ChargingGas is RequiringAuthorization, SafeMath { /** 1 EDG has 5 decimals **/ uint public constant oneEDG = 100000; /** the price per kgas and GWei in tokens (with decimals) */ uint public gasPrice; /** the amount of gas used per transaction in kGas */ mapping(bytes4 => uint) public gasPerTx; /** the number of tokens (5 decimals) payed by the users to cover the gas cost */ uint public gasPayback; function ChargingGas(uint kGasPrice) internal{ //deposit, withdrawFor, updateChannel, updateBatch, transferToNewContract bytes4[5] memory signatures = [bytes4(0x3edd1128),0x9607610a, 0xde48ff52, 0xc97b6d1f, 0x6bf06fde]; //amount of gas consumed by the above methods in GWei uint[5] memory gasUsage = [uint(146), 100, 65, 50, 85]; setGasUsage(signatures, gasUsage); setGasPrice(kGasPrice); } /** * sets the amount of gas consumed by methods with the given sigantures. * only called from the edgeless casino constructor. * @param signatures an array of method-signatures * gasNeeded the amount of gas consumed by these methods * */ function setGasUsage(bytes4[5] signatures, uint[5] gasNeeded) public onlyOwner { require(signatures.length == gasNeeded.length); for (uint8 i = 0; i < signatures.length; i++) gasPerTx[signatures[i]] = gasNeeded[i]; } /** * updates the price per 1000 gas in EDG. * @param price the new gas price (with decimals, max 0.1 EDG) **/ function setGasPrice(uint price) public onlyAuthorized { require(price < oneEDG/10); gasPrice = price; } /** * returns the gas cost of the called function. * */ function getGasCost() internal view returns(uint) { return safeMul(safeMul(gasPerTx[msg.sig], gasPrice), tx.gasprice) / 1000000000; } } contract CasinoBank is ChargingGas { /** the total balance of all players with virtual decimals **/ uint public playerBalance; /** the balance per player in edgeless tokens with virtual decimals */ mapping(address => uint) public balanceOf; /** in case the user wants/needs to call the withdraw function from his own wallet, he first needs to request a withdrawal */ mapping(address => uint) public withdrawAfter; /** a number to count withdrawal signatures to ensure each signature is different even if withdrawing the same amount to the same address */ mapping(address => uint) public withdrawCount; /** the maximum amount of tokens the user is allowed to deposit (with decimals) */ uint public maxDeposit; /** the maximum withdrawal of tokens the user is allowed to withdraw on one day (only enforced when the tx is not sent from an authorized wallet) **/ uint public maxWithdrawal; /** waiting time for withdrawal if not requested via the server **/ uint public waitingTime; /** the address of the predecessor **/ address public predecessor; /** informs listeners how many tokens were deposited for a player */ event Deposit(address _player, uint _numTokens, uint _gasCost); /** informs listeners how many tokens were withdrawn from the player to the receiver address */ event Withdrawal(address _player, address _receiver, uint _numTokens, uint _gasCost); /** * Constructor. * @param depositLimit the maximum deposit allowed * predecessorAddr the address of the predecessing contract * */ function CasinoBank(uint depositLimit, address predecessorAddr) internal { maxDeposit = depositLimit * oneEDG; maxWithdrawal = maxDeposit; waitingTime = 24 hours; predecessor = predecessorAddr; } /** * accepts deposits for an arbitrary address. * retrieves tokens from the message sender and adds them to the balance of the specified address. * edgeless tokens do not have any decimals, but are represented on this contract with decimals. * @param receiver address of the receiver * numTokens number of tokens to deposit (0 decimals) * chargeGas indicates if the gas cost is subtracted from the user&#39;s edgeless token balance **/ function deposit(address receiver, uint numTokens, bool chargeGas) public isAlive { require(numTokens > 0); uint value = safeMul(numTokens, oneEDG); uint gasCost; if (chargeGas) { gasCost = getGasCost(); value = safeSub(value, gasCost); gasPayback = safeAdd(gasPayback, gasCost); } uint newBalance = safeAdd(balanceOf[receiver], value); require(newBalance <= maxDeposit); assert(edg.transferFrom(msg.sender, address(this), numTokens)); balanceOf[receiver] = newBalance; playerBalance = safeAdd(playerBalance, value); emit Deposit(receiver, numTokens, gasCost); } /** * If the user wants/needs to withdraw his funds himself, he needs to request the withdrawal first. * This method sets the earliest possible withdrawal date to &#39;waitingTime from now (default 90m, but up to 24h). * Reason: The user should not be able to withdraw his funds, while the the last game methods have not yet been mined. **/ function requestWithdrawal() public { withdrawAfter[msg.sender] = now + waitingTime; } /** * In case the user requested a withdrawal and changes his mind. * Necessary to be able to continue playing. **/ function cancelWithdrawalRequest() public { withdrawAfter[msg.sender] = 0; } /** * withdraws an amount from the user balance if the waiting time passed since the request. * @param amount the amount of tokens to withdraw **/ function withdraw(uint amount) public keepAlive { require(amount <= maxWithdrawal); require(withdrawAfter[msg.sender] > 0 && now > withdrawAfter[msg.sender]); withdrawAfter[msg.sender] = 0; uint value = safeMul(amount, oneEDG); balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], value); playerBalance = safeSub(playerBalance, value); assert(edg.transfer(msg.sender, amount)); emit Withdrawal(msg.sender, msg.sender, amount, 0); } /** * lets the owner withdraw from the bankroll * @param receiver the receiver&#39;s address * numTokens the number of tokens to withdraw (0 decimals) **/ function withdrawBankroll(address receiver, uint numTokens) public onlyAuthorized { require(numTokens <= bankroll()); require(allowedReceiver[receiver]); assert(edg.transfer(receiver, numTokens)); } /** * withdraw the gas payback to the owner **/ function withdrawGasPayback() public onlyAuthorized { uint payback = gasPayback / oneEDG; assert(payback > 0); gasPayback = safeSub(gasPayback, payback * oneEDG); assert(edg.transfer(owner, payback)); } /** * returns the current bankroll in tokens with 0 decimals **/ function bankroll() view public returns(uint) { return safeSub(edg.balanceOf(address(this)), safeAdd(playerBalance, gasPayback) / oneEDG); } /** * updates the maximum deposit. * @param newMax the new maximum deposit (0 decimals) **/ function setMaxDeposit(uint newMax) public onlyAuthorized { maxDeposit = newMax * oneEDG; } /** * updates the maximum withdrawal. * @param newMax the new maximum withdrawal (0 decimals) **/ function setMaxWithdrawal(uint newMax) public onlyAuthorized { maxWithdrawal = newMax * oneEDG; } /** * sets the time the player has to wait for his funds to be unlocked before withdrawal (if not withdrawing with help of the casino server). * the time may not be longer than 24 hours. * @param newWaitingTime the new waiting time in seconds * */ function setWaitingTime(uint newWaitingTime) public onlyAuthorized { require(newWaitingTime <= 24 hours); waitingTime = newWaitingTime; } /** * transfers an amount from the contract balance to the owner&#39;s wallet. * @param receiver the receiver address * amount the amount of tokens to withdraw (0 decimals) * v,r,s the signature of the player **/ function withdrawFor(address receiver, uint amount, uint8 v, bytes32 r, bytes32 s) public onlyAuthorized keepAlive { address player = ecrecover(keccak256(receiver, amount, withdrawCount[receiver]), v, r, s); withdrawCount[receiver]++; uint gasCost = getGasCost(); uint value = safeAdd(safeMul(amount, oneEDG), gasCost); gasPayback = safeAdd(gasPayback, gasCost); balanceOf[player] = safeSub(balanceOf[player], value); playerBalance = safeSub(playerBalance, value); assert(edg.transfer(receiver, amount)); emit Withdrawal(player, receiver, amount, gasCost); } /** * transfers the player&#39;s tokens directly to the new casino contract after an update. * @param newCasino the address of the new casino contract * v, r, s the signature of the player * chargeGas indicates if the gas cost is payed by the player. * */ function transferToNewContract(address newCasino, uint8 v, bytes32 r, bytes32 s, bool chargeGas) public onlyAuthorized keepAlive { address player = ecrecover(keccak256(address(this), newCasino), v, r, s); uint gasCost = 0; if(chargeGas) gasCost = getGasCost(); uint value = safeSub(balanceOf[player], gasCost); require(value > oneEDG); //fractions of one EDG cannot be withdrawn value /= oneEDG; playerBalance = safeSub(playerBalance, balanceOf[player]); balanceOf[player] = 0; assert(edg.transfer(newCasino, value)); emit Withdrawal(player, newCasino, value, gasCost); CasinoBank cb = CasinoBank(newCasino); assert(cb.credit(player, value)); } /** * receive a player balance from the predecessor contract. * @param player the address of the player to credit the value for * value the number of tokens to credit (0 decimals) * */ function credit(address player, uint value) public returns(bool) { require(msg.sender == predecessor); uint valueWithDecimals = safeMul(value, oneEDG); balanceOf[player] = safeAdd(balanceOf[player], valueWithDecimals); playerBalance = safeAdd(playerBalance, valueWithDecimals); emit Deposit(player, value, 0); return true; } /** * lets the owner close the contract if there are no player funds on it or if nobody has been using it for at least 30 days * */ function close() public onlyOwner { closeContract(playerBalance); } } contract EdgelessCasino is CasinoBank{ /** the most recent known state of a state channel */ mapping(address => State) public lastState; /** fired when the state is updated */ event StateUpdate(address player, uint128 count, int128 winBalance, int difference, uint gasCost); /** fired if one of the parties chooses to log the seeds and results */ event GameData(address player, bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint gasCost); struct State{ uint128 count; int128 winBalance; } /** * creates a new edgeless casino contract. * @param predecessorAddress the address of the predecessing contract * tokenContract the address of the Edgeless token contract * depositLimit the maximum deposit allowed * kGasPrice the price per kGas in WEI **/ function EdgelessCasino(address predecessorAddress, address tokenContract, uint depositLimit, uint kGasPrice) CasinoBank(depositLimit, predecessorAddress) Mortal(tokenContract) ChargingGas(kGasPrice) public{ } /** * updates several state channels at once. can be called by authorized wallets only. * 1. determines the player address from the signature. * 2. verifies if the signed game-count is higher than the last known game-count of this channel. * 3. updates the balances accordingly. This means: It checks the already performed updates for this channel and computes * the new balance difference to add or subtract from the player‘s balance. * @param winBalances array of the current wins or losses * gameCounts array of the numbers of signed game moves * v,r,s array of the players&#39;s signatures * chargeGas indicates if the gas costs should be subtracted from the players&#39;s balances * */ function updateBatch(int128[] winBalances, uint128[] gameCounts, uint8[] v, bytes32[] r, bytes32[] s, bool chargeGas) public onlyAuthorized{ require(winBalances.length == gameCounts.length); require(winBalances.length == v.length); require(winBalances.length == r.length); require(winBalances.length == s.length); require(winBalances.length <= 50); address player; uint gasCost = 0; if(chargeGas) gasCost = getGasCost(); gasPayback = safeAdd(gasPayback, safeMul(gasCost, winBalances.length)); for(uint8 i = 0; i < winBalances.length; i++){ player = ecrecover(keccak256(winBalances[i], gameCounts[i]), v[i], r[i], s[i]); _updateState(player, winBalances[i], gameCounts[i], gasCost); } } /** * updates a state channel. can be called by both parties. * 1. verifies the signature. * 2. verifies if the signed game-count is higher than the last known game-count of this channel. * 3. updates the balances accordingly. This means: It checks the already performed updates for this channel and computes * the new balance difference to add or subtract from the player‘s balance. * @param winBalance the current win or loss * gameCount the number of signed game moves * v,r,s the signature of either the casino or the player * chargeGas indicates if the gas costs should be subtracted from the player&#39;s balance * */ function updateState(int128 winBalance, uint128 gameCount, uint8 v, bytes32 r, bytes32 s, bool chargeGas) public{ address player = determinePlayer(winBalance, gameCount, v, r, s); uint gasCost = 0; if(player == msg.sender)//if the player closes the state channel himself, make sure the signer is a casino wallet require(authorized[ecrecover(keccak256(player, winBalance, gameCount), v, r, s)]); else if (chargeGas){//subtract the gas costs from the player balance only if the casino wallet is the sender gasCost = getGasCost(); gasPayback = safeAdd(gasPayback, gasCost); } _updateState(player, winBalance, gameCount, gasCost); } /** * internal method to perform the actual state update. * @param player the player address * winBalance the player&#39;s win balance * gameCount the player&#39;s game count * */ function _updateState(address player, int128 winBalance, uint128 gameCount, uint gasCost) internal { State storage last = lastState[player]; require(gameCount > last.count); int difference = updatePlayerBalance(player, winBalance, last.winBalance, gasCost); lastState[player] = State(gameCount, winBalance); emit StateUpdate(player, gameCount, winBalance, difference, gasCost); } /** * determines if the msg.sender or the signer of the passed signature is the player. returns the player&#39;s address * @param winBalance the current winBalance, used to calculate the msg hash * gameCount the current gameCount, used to calculate the msg.hash * v, r, s the signature of the non-sending party * */ function determinePlayer(int128 winBalance, uint128 gameCount, uint8 v, bytes32 r, bytes32 s) view internal returns(address){ if (authorized[msg.sender])//casino is the sender -> player is the signer return ecrecover(keccak256(winBalance, gameCount), v, r, s); else return msg.sender; } /** * computes the difference of the win balance relative to the last known state and adds it to the player&#39;s balance. * in case the casino is the sender, the gas cost in EDG gets subtracted from the player&#39;s balance. * @param player the address of the player * winBalance the current win-balance * lastWinBalance the win-balance of the last known state * gasCost the gas cost of the tx * */ function updatePlayerBalance(address player, int128 winBalance, int128 lastWinBalance, uint gasCost) internal returns(int difference){ difference = safeSub(winBalance, lastWinBalance); int outstanding = safeSub(difference, int(gasCost)); uint outs; if(outstanding < 0){ outs = uint256(outstanding * (-1)); playerBalance = safeSub(playerBalance, outs); balanceOf[player] = safeSub(balanceOf[player], outs); } else{ outs = uint256(outstanding); assert(bankroll() * oneEDG > outs); playerBalance = safeAdd(playerBalance, outs); balanceOf[player] = safeAdd(balanceOf[player], outs); } } /** * logs some seeds and game results for players wishing to have their game history logged by the contract * @param serverSeeds array containing the server seeds * clientSeeds array containing the client seeds * results array containing the results * v, r, s the signature of the non-sending party (to make sure the correct results are logged) * */ function logGameData(bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint8 v, bytes32 r, bytes32 s) public{ address player = determinePlayer(serverSeeds, clientSeeds, results, v, r, s); uint gasCost; //charge gas in case the server is logging the results for the player if(player != msg.sender){ gasCost = (57 + 768 * serverSeeds.length / 1000)*gasPrice; balanceOf[player] = safeSub(balanceOf[player], gasCost); playerBalance = safeSub(playerBalance, gasCost); gasPayback = safeAdd(gasPayback, gasCost); } emit GameData(player, serverSeeds, clientSeeds, results, gasCost); } /** * determines if the msg.sender or the signer of the passed signature is the player. returns the player&#39;s address * @param serverSeeds array containing the server seeds * clientSeeds array containing the client seeds * results array containing the results * v, r, s the signature of the non-sending party * */ function determinePlayer(bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint8 v, bytes32 r, bytes32 s) view internal returns(address){ address signer = ecrecover(keccak256(serverSeeds, clientSeeds, results), v, r, s); if (authorized[msg.sender])//casino is the sender -> player is the signer return signer; else if (authorized[signer]) return msg.sender; else revert(); } }
contract can be closed by the owner anytime after this timestamp if non-zero / the edgeless token contract /
function Mortal(address tokenContract) internal{ edg = Token(tokenContract); }
6,636,112
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // Added public isInitialized() view of private initialized bool. // SPDX-License-Identifier: MIT pragma solidity 0.6.10; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } /** * @dev Return true if and only if the contract has been initialized * @return whether the contract has been initialized */ function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; interface IPoolFactory { function isPool(address pool) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {Address} from "Address.sol"; import {Context} from "Context.sol"; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {Initializable} from "Initializable.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 Initializable, 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. */ function __ERC20_initialize(string memory name, string memory symbol) internal initializer { _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 virtual view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero") ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function updateNameAndSymbol(string memory __name, string memory __symbol) internal { _name = __name; _symbol = __symbol; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ITrueLender2 { // @dev calculate overall value of the pools function value(ITrueFiPool2 pool) external view returns (uint256); // @dev distribute a basket of tokens for exiting user function distribute( address recipient, uint256 numerator, uint256 denominator ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface IERC20WithDecimals is IERC20 { function decimals() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20WithDecimals} from "IERC20WithDecimals.sol"; /** * @dev Oracle that converts any token to and from TRU * Used for liquidations and valuing of liquidated TRU in the pool */ interface ITrueFiPoolOracle { // token address function token() external view returns (IERC20WithDecimals); // amount of tokens 1 TRU is worth function truToToken(uint256 truAmount) external view returns (uint256); // amount of TRU 1 token is worth function tokenToTru(uint256 tokenAmount) external view returns (uint256); // USD price of token with 18 decimals function tokenToUsd(uint256 tokenAmount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; pragma experimental ABIEncoderV2; interface I1Inch3 { struct SwapDescription { address srcToken; address dstToken; address srcReceiver; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; } function swap( address caller, SwapDescription calldata desc, bytes calldata data ) external returns ( uint256 returnAmount, uint256 gasLeft, uint256 chiSpent ); function unoswap( address srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata /* pools */ ) external payable returns (uint256 returnAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ERC20, IERC20} from "UpgradeableERC20.sol"; import {ITrueLender2} from "ITrueLender2.sol"; import {ITrueFiPoolOracle} from "ITrueFiPoolOracle.sol"; import {I1Inch3} from "I1Inch3.sol"; interface ITrueFiPool2 is IERC20 { function initialize( ERC20 _token, ERC20 _stakingToken, ITrueLender2 _lender, I1Inch3 __1Inch, address __owner ) external; function token() external view returns (ERC20); function oracle() external view returns (ITrueFiPoolOracle); /** * @dev Join the pool by depositing tokens * @param amount amount of tokens to deposit */ function join(uint256 amount) external; /** * @dev borrow from pool * 1. Transfer TUSD to sender * 2. Only lending pool should be allowed to call this */ function borrow(uint256 amount) external; /** * @dev pay borrowed money back to pool * 1. Transfer TUSD from sender * 2. Only lending pool should be allowed to call this */ function repay(uint256 currencyAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ILoanFactory2 { function createLoanToken( ITrueFiPool2 _pool, uint256 _amount, uint256 _term, uint256 _apy ) external; function isLoanToken(address) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "Context.sol"; import "IERC20.sol"; import "SafeMath.sol"; import "Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "IERC20.sol"; import "SafeMath.sol"; import "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.10; import {IERC20} from "IERC20.sol"; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ILoanToken2 is IERC20 { enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated} function borrower() external view returns (address); function amount() external view returns (uint256); function term() external view returns (uint256); function apy() external view returns (uint256); function start() external view returns (uint256); function lender() external view returns (address); function debt() external view returns (uint256); function pool() external view returns (ITrueFiPool2); function profit() external view returns (uint256); function status() external view returns (Status); function getParameters() external view returns ( uint256, uint256, uint256 ); function fund() external; function withdraw(address _beneficiary) external; function settle() external; function enterDefault() external; function liquidate() external; function redeem(uint256 _amount) external; function repay(address _sender, uint256 _amount) external; function repayInFull(address _sender) external; function reclaim() external; function allowTransfer(address account, bool _status) external; function repaid() external view returns (uint256); function isRepaid() external view returns (bool); function balance() external view returns (uint256); function value(uint256 _balance) external view returns (uint256); function token() external view returns (IERC20); function version() external pure returns (uint8); } //interface IContractWithPool { // function pool() external view returns (ITrueFiPool2); //} // //// Had to be split because of multiple inheritance problem //interface ILoanToken2 is ILoanToken, IContractWithPool { // //} // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface ILoanToken is IERC20 { enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated} function borrower() external view returns (address); function amount() external view returns (uint256); function term() external view returns (uint256); function apy() external view returns (uint256); function start() external view returns (uint256); function lender() external view returns (address); function debt() external view returns (uint256); function profit() external view returns (uint256); function status() external view returns (Status); function borrowerFee() external view returns (uint256); function receivedAmount() external view returns (uint256); function isLoanToken() external pure returns (bool); function getParameters() external view returns ( uint256, uint256, uint256 ); function fund() external; function withdraw(address _beneficiary) external; function settle() external; function enterDefault() external; function liquidate() external; function redeem(uint256 _amount) external; function repay(address _sender, uint256 _amount) external; function repayInFull(address _sender) external; function reclaim() external; function allowTransfer(address account, bool _status) external; function repaid() external view returns (uint256); function isRepaid() external view returns (bool); function balance() external view returns (uint256); function value(uint256 _balance) external view returns (uint256); function currencyToken() external view returns (IERC20); function version() external pure returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ERC20} from "ERC20.sol"; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {SafeERC20} from "SafeERC20.sol"; import {ILoanToken} from "ILoanToken.sol"; /** * @title LoanToken * @dev A token which represents share of a debt obligation * * Each LoanToken has: * - borrower address * - borrow amount * - loan term * - loan APY * * Loan progresses through the following states: * Awaiting: Waiting for funding to meet capital requirements * Funded: Capital requirements met, borrower can withdraw * Withdrawn: Borrower withdraws money, loan waiting to be repaid * Settled: Loan has been paid back in full with interest * Defaulted: Loan has not been paid back in full * Liquidated: Loan has Defaulted and stakers have been Liquidated * * - LoanTokens are non-transferable except for whitelisted addresses * - This version of LoanToken only supports a single funder */ contract LoanToken is ILoanToken, ERC20 { using SafeMath for uint256; using SafeERC20 for IERC20; uint128 public constant lastMinutePaybackDuration = 1 days; address public override borrower; address public liquidator; uint256 public override amount; uint256 public override term; uint256 public override apy; uint256 public override start; address public override lender; uint256 public override debt; uint256 public redeemed; // borrow fee -> 25 = 0.25% uint256 public override borrowerFee = 25; // whitelist for transfers mapping(address => bool) public canTransfer; Status public override status; IERC20 public override currencyToken; /** * @dev Emitted when the loan is funded * @param lender Address which funded the loan */ event Funded(address lender); /** * @dev Emitted when transfer whitelist is updated * @param account Account to whitelist for transfers * @param status New whitelist status */ event TransferAllowanceChanged(address account, bool status); /** * @dev Emitted when borrower withdraws funds * @param beneficiary Account which will receive funds */ event Withdrawn(address beneficiary); /** * @dev Emitted when loan has been fully repaid * @param returnedAmount Amount that was returned */ event Settled(uint256 returnedAmount); /** * @dev Emitted when term is over without full repayment * @param returnedAmount Amount that was returned before expiry */ event Defaulted(uint256 returnedAmount); /** * @dev Emitted when a LoanToken is redeemed for underlying currencyTokens * @param receiver Receiver of currencyTokens * @param burnedAmount Amount of LoanTokens burned * @param redeemedAmount Amount of currencyToken received */ event Redeemed(address receiver, uint256 burnedAmount, uint256 redeemedAmount); /** * @dev Emitted when a LoanToken is repaid by the borrower in underlying currencyTokens * @param repayer Sender of currencyTokens * @param repaidAmount Amount of currencyToken repaid */ event Repaid(address repayer, uint256 repaidAmount); /** * @dev Emitted when borrower reclaims remaining currencyTokens * @param borrower Receiver of remaining currencyTokens * @param reclaimedAmount Amount of currencyTokens repaid */ event Reclaimed(address borrower, uint256 reclaimedAmount); /** * @dev Emitted when loan gets liquidated * @param status Final loan status */ event Liquidated(Status status); /** * @dev Create a Loan * @param _currencyToken Token to lend * @param _borrower Borrower address * @param _amount Borrow amount of currency tokens * @param _term Loan length * @param _apy Loan APY */ constructor( IERC20 _currencyToken, address _borrower, address _lender, address _liquidator, uint256 _amount, uint256 _term, uint256 _apy ) public ERC20("Loan Token", "LOAN") { require(_lender != address(0), "LoanToken: Lender is not set"); currencyToken = _currencyToken; borrower = _borrower; liquidator = _liquidator; amount = _amount; term = _term; apy = _apy; lender = _lender; debt = interest(amount); } /** * @dev Only borrower can withdraw & repay loan */ modifier onlyBorrower() { require(msg.sender == borrower, "LoanToken: Caller is not the borrower"); _; } /** * @dev Only liquidator can liquidate */ modifier onlyLiquidator() { require(msg.sender == liquidator, "LoanToken: Caller is not the liquidator"); _; } /** * @dev Only after loan has been closed: Settled, Defaulted, or Liquidated */ modifier onlyAfterClose() { require(status >= Status.Settled, "LoanToken: Only after loan has been closed"); _; } /** * @dev Only when loan is Funded */ modifier onlyOngoing() { require(status == Status.Funded || status == Status.Withdrawn, "LoanToken: Current status should be Funded or Withdrawn"); _; } /** * @dev Only when loan is Funded */ modifier onlyFunded() { require(status == Status.Funded, "LoanToken: Current status should be Funded"); _; } /** * @dev Only when loan is Withdrawn */ modifier onlyAfterWithdraw() { require(status >= Status.Withdrawn, "LoanToken: Only after loan has been withdrawn"); _; } /** * @dev Only when loan is Awaiting */ modifier onlyAwaiting() { require(status == Status.Awaiting, "LoanToken: Current status should be Awaiting"); _; } /** * @dev Only when loan is Defaulted */ modifier onlyDefaulted() { require(status == Status.Defaulted, "LoanToken: Current status should be Defaulted"); _; } /** * @dev Only whitelisted accounts or lender */ modifier onlyWhoCanTransfer(address sender) { require( sender == lender || canTransfer[sender], "LoanToken: This can be performed only by lender or accounts allowed to transfer" ); _; } /** * @dev Only lender can perform certain actions */ modifier onlyLender() { require(msg.sender == lender, "LoanToken: This can be performed only by lender"); _; } /** * @dev Return true if this contract is a LoanToken * @return True if this contract is a LoanToken */ function isLoanToken() external override pure returns (bool) { return true; } /** * @dev Get loan parameters * @return amount, term, apy */ function getParameters() external override view returns ( uint256, uint256, uint256 ) { return (amount, apy, term); } /** * @dev Get coupon value of this loan token in currencyToken * This assumes the loan will be paid back on time, with interest * @param _balance number of LoanTokens to get value for * @return coupon value of _balance LoanTokens in currencyTokens */ function value(uint256 _balance) external override view returns (uint256) { if (_balance == 0) { return 0; } uint256 passed = block.timestamp.sub(start); if (passed > term || status == Status.Settled) { passed = term; } // assume year is 365 days uint256 interest = amount.mul(apy).mul(passed).div(365 days).div(10000); return amount.add(interest).mul(_balance).div(debt); } /** * @dev Fund a loan * Set status, start time, lender */ function fund() external override onlyAwaiting onlyLender { status = Status.Funded; start = block.timestamp; _mint(msg.sender, debt); currencyToken.safeTransferFrom(msg.sender, address(this), receivedAmount()); emit Funded(msg.sender); } /** * @dev Whitelist accounts to transfer * @param account address to allow transfers for * @param _status true allows transfers, false disables transfers */ function allowTransfer(address account, bool _status) external override onlyLender { canTransfer[account] = _status; emit TransferAllowanceChanged(account, _status); } /** * @dev Borrower calls this function to withdraw funds * Sets the status of the loan to Withdrawn * @param _beneficiary address to send funds to */ function withdraw(address _beneficiary) external override onlyBorrower onlyFunded { status = Status.Withdrawn; currencyToken.safeTransfer(_beneficiary, receivedAmount()); emit Withdrawn(_beneficiary); } /** * @dev Settle the loan after checking it has been repaid */ function settle() public override onlyOngoing { require(isRepaid(), "LoanToken: loan must be repaid to settle"); status = Status.Settled; emit Settled(_balance()); } /** * @dev Default the loan if it has not been repaid by the end of term */ function enterDefault() external override onlyOngoing { require(!isRepaid(), "LoanToken: cannot default a repaid loan"); require(start.add(term).add(lastMinutePaybackDuration) <= block.timestamp, "LoanToken: Loan cannot be defaulted yet"); status = Status.Defaulted; emit Defaulted(_balance()); } /** * @dev Liquidate the loan if it has defaulted */ function liquidate() external override onlyDefaulted onlyLiquidator { status = Status.Liquidated; emit Liquidated(status); } /** * @dev Redeem LoanToken balances for underlying currencyToken * Can only call this function after the loan is Closed * @param _amount amount to redeem */ function redeem(uint256 _amount) external override onlyAfterClose { uint256 amountToReturn = _amount.mul(_balance()).div(totalSupply()); redeemed = redeemed.add(amountToReturn); _burn(msg.sender, _amount); currencyToken.safeTransfer(msg.sender, amountToReturn); emit Redeemed(msg.sender, _amount, amountToReturn); } /** * @dev Function for borrower to repay the loan * Borrower can repay at any time * @param _sender account sending currencyToken to repay * @param _amount amount of currencyToken to repay */ function repay(address _sender, uint256 _amount) external override { _repay(_sender, _amount); } /** * @dev Function for borrower to repay all of the remaining loan balance * Borrower should use this to ensure full repayment * @param _sender account sending currencyToken to repay */ function repayInFull(address _sender) external override { _repay(_sender, debt.sub(_balance())); } /** * @dev Internal function for loan repayment * If _amount is sufficient, then this also settles the loan * @param _sender account sending currencyToken to repay * @param _amount amount of currencyToken to repay */ function _repay(address _sender, uint256 _amount) internal onlyAfterWithdraw { require(_amount <= debt.sub(_balance()), "LoanToken: Cannot repay over the debt"); emit Repaid(_sender, _amount); currencyToken.safeTransferFrom(_sender, address(this), _amount); if (isRepaid()) { settle(); } } /** * @dev Function for borrower to reclaim stuck currencyToken * Can only call this function after the loan is Closed * and all of LoanToken holders have been burnt */ function reclaim() external override onlyAfterClose onlyBorrower { require(totalSupply() == 0, "LoanToken: Cannot reclaim when LoanTokens are in circulation"); uint256 balanceRemaining = _balance(); require(balanceRemaining > 0, "LoanToken: Cannot reclaim when balance 0"); currencyToken.safeTransfer(borrower, balanceRemaining); emit Reclaimed(borrower, balanceRemaining); } /** * @dev Check how much was already repaid * Funds stored on the contract's address plus funds already redeemed by lenders * @return Uint256 representing what value was already repaid */ function repaid() external override view onlyAfterWithdraw returns (uint256) { return _balance().add(redeemed); } /** * @dev Check whether an ongoing loan has been repaid in full * @return true if and only if this loan has been repaid */ function isRepaid() public override view onlyOngoing returns (bool) { return _balance() >= debt; } /** * @dev Public currency token balance function * @return currencyToken balance of this contract */ function balance() external override view returns (uint256) { return _balance(); } /** * @dev Get currency token balance for this contract * @return currencyToken balance of this contract */ function _balance() internal view returns (uint256) { return currencyToken.balanceOf(address(this)); } /** * @dev Calculate amount borrowed minus fee * @return Amount minus fees */ function receivedAmount() public override view returns (uint256) { return amount.sub(amount.mul(borrowerFee).div(10000)); } /** * @dev Calculate interest that will be paid by this loan for an amount (returned funds included) * amount + ((amount * apy * term) / (365 days / precision)) * @param _amount amount * @return uint256 Amount of interest paid for _amount */ function interest(uint256 _amount) internal view returns (uint256) { return _amount.add(_amount.mul(apy).mul(term).div(365 days).div(10000)); } /** * @dev get profit for this loan * @return profit for this loan */ function profit() external override view returns (uint256) { return debt.sub(amount); } /** * @dev Override ERC20 _transfer so only whitelisted addresses can transfer * @param sender sender of the transaction * @param recipient recipient of the transaction * @param _amount amount to send */ function _transfer( address sender, address recipient, uint256 _amount ) internal override onlyWhoCanTransfer(sender) { return super._transfer(sender, recipient, _amount); } function version() external virtual override pure returns (uint8) { return 3; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ERC20} from "ERC20.sol"; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {SafeERC20} from "SafeERC20.sol"; import {ILoanToken2, ITrueFiPool2} from "ILoanToken2.sol"; import {LoanToken} from "LoanToken.sol"; /** * @title LoanToken V2 * @dev A token which represents share of a debt obligation * * Each LoanToken has: * - borrower address * - borrow amount * - loan term * - loan APY * * Loan progresses through the following states: * Awaiting: Waiting for funding to meet capital requirements * Funded: Capital requirements met, borrower can withdraw * Withdrawn: Borrower withdraws money, loan waiting to be repaid * Settled: Loan has been paid back in full with interest * Defaulted: Loan has not been paid back in full * Liquidated: Loan has Defaulted and stakers have been Liquidated * * - LoanTokens are non-transferable except for whitelisted addresses * - This version of LoanToken only supports a single funder */ contract LoanToken2 is ILoanToken2, ERC20 { using SafeMath for uint256; using SafeERC20 for IERC20; uint128 public constant LAST_MINUTE_PAYBACK_DURATION = 1 days; uint256 private constant APY_PRECISION = 10000; address public override borrower; address public liquidator; uint256 public override amount; uint256 public override term; // apy precision: 10000 = 100% uint256 public override apy; uint256 public override start; address public override lender; uint256 public override debt; uint256 public redeemed; // whitelist for transfers mapping(address => bool) public canTransfer; Status public override status; IERC20 public override token; ITrueFiPool2 public override pool; /** * @dev Emitted when the loan is funded * @param lender Address which funded the loan */ event Funded(address lender); /** * @dev Emitted when transfer whitelist is updated * @param account Account to whitelist for transfers * @param status New whitelist status */ event TransferAllowanceChanged(address account, bool status); /** * @dev Emitted when borrower withdraws funds * @param beneficiary Account which will receive funds */ event Withdrawn(address beneficiary); /** * @dev Emitted when loan has been fully repaid * @param returnedAmount Amount that was returned */ event Settled(uint256 returnedAmount); /** * @dev Emitted when term is over without full repayment * @param returnedAmount Amount that was returned before expiry */ event Defaulted(uint256 returnedAmount); /** * @dev Emitted when a LoanToken is redeemed for underlying tokens * @param receiver Receiver of tokens * @param burnedAmount Amount of LoanTokens burned * @param redeemedAmount Amount of token received */ event Redeemed(address receiver, uint256 burnedAmount, uint256 redeemedAmount); /** * @dev Emitted when a LoanToken is repaid by the borrower in underlying tokens * @param repayer Sender of tokens * @param repaidAmount Amount of token repaid */ event Repaid(address repayer, uint256 repaidAmount); /** * @dev Emitted when borrower reclaims remaining tokens * @param borrower Receiver of remaining tokens * @param reclaimedAmount Amount of tokens repaid */ event Reclaimed(address borrower, uint256 reclaimedAmount); /** * @dev Emitted when loan gets liquidated * @param status Final loan status */ event Liquidated(Status status); /** * @dev Create a Loan * @param _pool Pool to lend from * @param _borrower Borrower address * @param _lender Lender address * @param _liquidator Liquidator address * @param _amount Borrow amount of loaned tokens * @param _term Loan length * @param _apy Loan APY */ constructor( ITrueFiPool2 _pool, address _borrower, address _lender, address _liquidator, uint256 _amount, uint256 _term, uint256 _apy ) public ERC20("TrueFi Loan Token", "LOAN") { require(_lender != address(0), "LoanToken2: Lender is not set"); pool = _pool; token = _pool.token(); borrower = _borrower; liquidator = _liquidator; amount = _amount; term = _term; apy = _apy; lender = _lender; debt = interest(amount); } /** * @dev Only borrower can withdraw & repay loan */ modifier onlyBorrower() { require(msg.sender == borrower, "LoanToken2: Caller is not the borrower"); _; } /** * @dev Only liquidator can liquidate */ modifier onlyLiquidator() { require(msg.sender == liquidator, "LoanToken2: Caller is not the liquidator"); _; } /** * @dev Only after loan has been closed: Settled, Defaulted, or Liquidated */ modifier onlyAfterClose() { require(status >= Status.Settled, "LoanToken2: Only after loan has been closed"); _; } /** * @dev Only when loan is Funded */ modifier onlyOngoing() { require(status == Status.Funded || status == Status.Withdrawn, "LoanToken2: Current status should be Funded or Withdrawn"); _; } /** * @dev Only when loan is Funded */ modifier onlyFunded() { require(status == Status.Funded, "LoanToken2: Current status should be Funded"); _; } /** * @dev Only when loan is Withdrawn */ modifier onlyAfterWithdraw() { require(status >= Status.Withdrawn, "LoanToken2: Only after loan has been withdrawn"); _; } /** * @dev Only when loan is Awaiting */ modifier onlyAwaiting() { require(status == Status.Awaiting, "LoanToken2: Current status should be Awaiting"); _; } /** * @dev Only when loan is Defaulted */ modifier onlyDefaulted() { require(status == Status.Defaulted, "LoanToken2: Current status should be Defaulted"); _; } /** * @dev Only whitelisted accounts or lender */ modifier onlyWhoCanTransfer(address sender) { require( sender == lender || canTransfer[sender], "LoanToken2: This can be performed only by lender or accounts allowed to transfer" ); _; } /** * @dev Only lender can perform certain actions */ modifier onlyLender() { require(msg.sender == lender, "LoanToken2: This can be performed only by lender"); _; } /** * @dev Get loan parameters * @return amount, term, apy */ function getParameters() external override view returns ( uint256, uint256, uint256 ) { return (amount, apy, term); } /** * @dev Get coupon value of this loan token in token * This assumes the loan will be paid back on time, with interest * @param _balance number of LoanTokens to get value for * @return coupon value of _balance LoanTokens in tokens */ function value(uint256 _balance) external override view returns (uint256) { if (_balance == 0) { return 0; } uint256 passed = block.timestamp.sub(start); if (passed > term || status == Status.Settled) { passed = term; } // assume year is 365 days uint256 interest = amount.mul(apy).mul(passed).div(365 days).div(APY_PRECISION); return amount.add(interest).mul(_balance).div(debt); } /** * @dev Fund a loan * Set status, start time, lender */ function fund() external override onlyAwaiting onlyLender { status = Status.Funded; start = block.timestamp; _mint(msg.sender, debt); token.safeTransferFrom(msg.sender, address(this), amount); emit Funded(msg.sender); } /** * @dev Whitelist accounts to transfer * @param account address to allow transfers for * @param _status true allows transfers, false disables transfers */ function allowTransfer(address account, bool _status) external override onlyLender { canTransfer[account] = _status; emit TransferAllowanceChanged(account, _status); } /** * @dev Borrower calls this function to withdraw funds * Sets the status of the loan to Withdrawn * @param _beneficiary address to send funds to */ function withdraw(address _beneficiary) external override onlyBorrower onlyFunded { status = Status.Withdrawn; token.safeTransfer(_beneficiary, amount); emit Withdrawn(_beneficiary); } /** * @dev Settle the loan after checking it has been repaid */ function settle() public override onlyOngoing { require(isRepaid(), "LoanToken2: loan must be repaid to settle"); status = Status.Settled; emit Settled(_balance()); } /** * @dev Default the loan if it has not been repaid by the end of term */ function enterDefault() external override onlyOngoing { require(!isRepaid(), "LoanToken2: cannot default a repaid loan"); require(start.add(term).add(LAST_MINUTE_PAYBACK_DURATION) <= block.timestamp, "LoanToken2: Loan cannot be defaulted yet"); status = Status.Defaulted; emit Defaulted(_balance()); } /** * @dev Liquidate the loan if it has defaulted */ function liquidate() external override onlyDefaulted onlyLiquidator { status = Status.Liquidated; emit Liquidated(status); } /** * @dev Redeem LoanToken balances for underlying token * Can only call this function after the loan is Closed * @param _amount amount to redeem */ function redeem(uint256 _amount) external override onlyAfterClose { uint256 amountToReturn = _amount.mul(_balance()).div(totalSupply()); redeemed = redeemed.add(amountToReturn); _burn(msg.sender, _amount); token.safeTransfer(msg.sender, amountToReturn); emit Redeemed(msg.sender, _amount, amountToReturn); } /** * @dev Function for borrower to repay the loan * Borrower can repay at any time * @param _sender account sending token to repay * @param _amount amount of token to repay */ function repay(address _sender, uint256 _amount) external override { _repay(_sender, _amount); } /** * @dev Function for borrower to repay all of the remaining loan balance * Borrower should use this to ensure full repayment * @param _sender account sending token to repay */ function repayInFull(address _sender) external override { _repay(_sender, debt.sub(_balance())); } /** * @dev Internal function for loan repayment * If _amount is sufficient, then this also settles the loan * @param _sender account sending token to repay * @param _amount amount of token to repay */ function _repay(address _sender, uint256 _amount) internal onlyAfterWithdraw { require(_amount <= debt.sub(_balance()), "LoanToken2: Cannot repay over the debt"); emit Repaid(_sender, _amount); token.safeTransferFrom(_sender, address(this), _amount); if (isRepaid()) { settle(); } } /** * @dev Function for borrower to reclaim stuck token * Can only call this function after the loan is Closed * and all of LoanToken holders have been burnt */ function reclaim() external override onlyAfterClose onlyBorrower { require(totalSupply() == 0, "LoanToken2: Cannot reclaim when LoanTokens are in circulation"); uint256 balanceRemaining = _balance(); require(balanceRemaining > 0, "LoanToken2: Cannot reclaim when balance 0"); token.safeTransfer(borrower, balanceRemaining); emit Reclaimed(borrower, balanceRemaining); } /** * @dev Check how much was already repaid * Funds stored on the contract's address plus funds already redeemed by lenders * @return Uint256 representing what value was already repaid */ function repaid() external override view onlyAfterWithdraw returns (uint256) { return _balance().add(redeemed); } /** * @dev Check whether an ongoing loan has been repaid in full * @return true if and only if this loan has been repaid */ function isRepaid() public override view onlyOngoing returns (bool) { return _balance() >= debt; } /** * @dev Public currency token balance function * @return token balance of this contract */ function balance() external override view returns (uint256) { return _balance(); } /** * @dev Get currency token balance for this contract * @return token balance of this contract */ function _balance() internal view returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Calculate interest that will be paid by this loan for an amount (returned funds included) * amount + ((amount * apy * term) / 365 days / precision) * @param _amount amount * @return uint256 Amount of interest paid for _amount */ function interest(uint256 _amount) internal view returns (uint256) { return _amount.add(_amount.mul(apy).mul(term).div(365 days).div(APY_PRECISION)); } /** * @dev get profit for this loan * @return profit for this loan */ function profit() external override view returns (uint256) { return debt.sub(amount); } /** * @dev Override ERC20 _transfer so only whitelisted addresses can transfer * @param sender sender of the transaction * @param recipient recipient of the transaction * @param _amount amount to send */ function _transfer( address sender, address recipient, uint256 _amount ) internal override onlyWhoCanTransfer(sender) { return super._transfer(sender, recipient, _amount); } function version() external override pure returns (uint8) { return 4; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {Initializable} from "Initializable.sol"; import {IPoolFactory} from "IPoolFactory.sol"; import {ILoanFactory2} from "ILoanFactory2.sol"; import {ITrueFiPool2} from "ITrueFiPool2.sol"; import {LoanToken2, IERC20} from "LoanToken2.sol"; /** * @title LoanFactory2 * @notice Deploy LoanTokens for pools created by PoolFactory, with this Contract * @dev LoanTokens are deployed through a factory to ensure that all * LoanTokens adhere to the same contract code, rather than using an interface. */ contract LoanFactory2 is ILoanFactory2, Initializable { // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== // @dev Track Valid LoanTokens mapping(address => bool) public override isLoanToken; IPoolFactory public poolFactory; address public lender; address public liquidator; // ======= STORAGE DECLARATION END ============ /** * @dev Emitted when a LoanToken is created * @param contractAddress LoanToken contract address */ event LoanTokenCreated(address contractAddress); /** * @dev Initialize this contract and set currency token * @param _poolFactory PoolFactory address * @param _lender Lender address * @param _liquidator Liquidator address */ function initialize( IPoolFactory _poolFactory, address _lender, address _liquidator ) external initializer { poolFactory = _poolFactory; lender = _lender; liquidator = _liquidator; } /** * @dev Deploy LoanToken with parameters * @param _amount Amount to borrow * @param _term Length of loan * @param _apy Loan yield */ function createLoanToken( ITrueFiPool2 _pool, uint256 _amount, uint256 _term, uint256 _apy ) external override { require(_amount > 0, "LoanFactory: Loans of amount 0, will not be approved"); require(_term > 0, "LoanFactory: Loans cannot have instantaneous term of repay"); require(poolFactory.isPool(address(_pool)), "LoanFactory: Pool was not created by PoolFactory"); address newToken = address(new LoanToken2(_pool, msg.sender, lender, liquidator, _amount, _term, _apy)); isLoanToken[newToken] = true; emit LoanTokenCreated(newToken); } }
Calculate amount borrowed minus fee return Amount minus fees/
function receivedAmount() public override view returns (uint256) { return amount.sub(amount.mul(borrowerFee).div(10000)); }
1,718,017
./full_match/137/0xe558726C468Ccc21cc09ca4B8B46131dC1002923/sources/project_/contracts/Exchange.sol
Reverse the base and quote assets in an internally tracked liquidity pool baseAssetAddress The base asset address quoteAssetAddress The quote asset address/
function reverseLiquidityPoolAssets( address baseAssetAddress, address quoteAssetAddress ) external onlyAdmin { _liquidityPools.reverseLiquidityPoolAssets( baseAssetAddress, quoteAssetAddress ); emit LiquidityPoolAssetsReversed(baseAssetAddress, quoteAssetAddress); }
4,761,983
./full_match/7700/0xb67341E8159F130006881856F9565433f6b5CE7f/sources/contracts/CPMSMessageRenderer.sol
Our one shared message representation.
function tokenURI(uint256 tokenId, string calldata body, address sender, uint256 stampId, uint256 sentAt, address recipient) public pure returns (string memory) { }
4,649,218
/* Implementation of contract EulerRoot */ pragma ton-solidity >= 0.32.0; pragma AbiHeader expire; pragma AbiHeader pubkey; import "./IEulerRoot.sol"; import "EulerProblem.sol"; import "EulerUser.sol"; import "RecoverablePubkey.sol.gen"; contract EulerRoot is IEulerRoot, RecoverablePubkey { uint64 constant EXN_AUTH_FAILED = 100 ; uint64 constant EXN_NOT_ENOUGH_VALUE = 101 ; /// @dev This event is emitted everytime a user solves a problem event ProblemSolved( uint32 problem, uint256 pubkey ); // The owner of this contract, who can create new EulerProblem // contracts uint256 g_owner ; // The code of EulerProblem contracts TvmCell g_problem_code ; // The code of EulerUser contracts TvmCell g_user_code ; /// @dev The user must only provide the codes of EulerProblem and /// EulerUser contracts constructor( TvmCell problem_code, TvmCell user_code ) public { require( msg.pubkey() == tvm.pubkey(), EXN_AUTH_FAILED ); require( address(this).balance >= 2 ton, EXN_NOT_ENOUGH_VALUE ); tvm.accept(); g_owner = msg.pubkey() ; g_problem_code = problem_code ; g_user_code = user_code ; } /// @dev Deploys a EulerProblem contract for a new Euler problem. Only the /// owner of the EulerRoot can call this function. /// @param problem The number of the problem /// @param verifkey The Groth16 verification key of the problem /// @param zip_provkey A compressed version of the Groth16 proving key /// of the problem, used to create a submission locally /// @param nonce The nonce that the user must provide with his submission /// @param title The title of the problem /// @param description The description of the problem /// @param url The link to the problem official description function new_problem( uint32 problem, bytes verifkey, bytes zip_provkey, string nonce, string title, string description, string url) public view returns ( address addr ) { require( g_owner == msg.pubkey(), EXN_AUTH_FAILED ); require( address(this).balance > 1 ton, EXN_NOT_ENOUGH_VALUE ); tvm.accept() ; addr = new EulerProblem { value: 1 ton, pubkey: tvm.pubkey() , code: g_problem_code , varInit: { s_problem: problem , s_root_contract: this } }( verifkey, zip_provkey, nonce, title, description, url ); } /// @dev This function deploys a EulerUser contract associated with a /// given public key. Anybody can call this function from a multisig. /// @param pubkey: The user pubkey function new_user( uint256 pubkey ) public view returns ( address addr ) { require( msg.value >= 1 ton, EXN_AUTH_FAILED ); addr = new EulerUser { value: msg.value - 0.1 ton, pubkey: pubkey , code: g_user_code , varInit: { s_root_contract: this } }() ; } /// @dev Returns the address of the EulerProblem contract associated /// with a given problem number. The contract exists only if /// 'new_problem' has been called before. /// @param problem : the number of the problem function problem_address( uint32 problem ) public view returns ( address addr ) { TvmCell stateInit = tvm.buildStateInit({ contr: EulerProblem , pubkey: tvm.pubkey() , code: g_problem_code , varInit: { s_problem: problem , s_root_contract: this } }); addr = address(tvm.hash(stateInit)); } /// @dev returns the address of the EulerUser contract associated /// with a given pubkey. The contract only exists if 'new_user' has /// been called before. function user_address( uint256 pubkey ) public view returns ( address addr ) { TvmCell stateInit = tvm.buildStateInit({ contr: EulerUser , pubkey: pubkey , code: g_user_code , varInit: { s_root_contract: this } }); addr = address(tvm.hash(stateInit)); } /// @dev submits a solution to a given problem, using a proof /// generated by euler-client C++ program, associated with the /// given pubkey. The proof will fail if another pubkey is /// provided. /// @param problem: number of the problem /// @param proof: the 'proof.bin' generated by euler-client /// @param pubkey: the pubkey of the user, as used when generating /// 'proof.bin' function submit( uint32 problem, bytes proof, uint256 pubkey) public view override { address addr = problem_address( problem ); EulerProblem( addr ).submit { value:0, flag: 64} ( problem, proof, pubkey ); } /// @dev updates the Blueprint circuit associated with a given problem /// @param problem: the number of the problem /// @param verifkey: the new verification key of the circuit /// @param zip_provkey: the new proving key of the circuit to be used to /// generate submission proofs /// @param nonce: the nonce to be used to generate submission proofs function update_circuit( uint32 problem, bytes verifkey, bytes zip_provkey, string nonce ) public view { require( g_owner == msg.pubkey(), EXN_AUTH_FAILED ); tvm.accept(); address addr = problem_address( problem ); EulerProblem( addr ).update_circuit { value:0.2 ton } ( verifkey, zip_provkey, nonce ); } /// @dev Updates the description of a problem. Only called by the owner of /// the EulerRoot contract. /// @param problem: the number of the problem /// @param title: the new title of the problem or empty string /// @param description: the new description of the problem or empty string /// @param url: the new url of the problem or empty string function update_problem( uint32 problem, string title, string description, string url ) public view { require( g_owner == msg.pubkey(), EXN_AUTH_FAILED ); tvm.accept(); address addr = problem_address( problem ); EulerProblem( addr ).update_problem { value:0.2 ton } ( title, description, url ); } /// @dev This function is called by a EulerProblem when a user /// successfully submitted a solution. The function verifies that /// the sender is indeed an EulerProblem contract as expected. The /// function emits en event and calls the EulerUser contract to /// record the information /// @param problem: the number of the problem /// @param pubkey: the user pubkey who successfully solved the problem function has_solved( uint32 problem, uint256 pubkey ) public override { address addr = problem_address( problem ) ; require( addr == msg.sender, EXN_AUTH_FAILED ); emit ProblemSolved( problem, pubkey ); addr = user_address( pubkey ); EulerUser( addr ).has_solved{ value:0, flag: 64 }( problem ); } /// @dev This get-method function is used to recover information on /// this contract function get() public view returns ( uint256 owner, uint256 problem_code_hash, uint256 user_code_hash ) { owner = g_owner ; problem_code_hash = tvm.hash ( g_problem_code ); user_code_hash = tvm.hash ( g_user_code ); } /// @dev This internal function is used to change the owner of the /// contract using the pincode-client smart contract (described in /// 03-pincode section) function recover_pubkey ( uint256 oldkey, uint256 newkey) internal override { if( oldkey == g_owner ){ g_owner = newkey; } } }
submits a solution to a given problem, using a proof generated by euler-client C++ program, associated with the given pubkey. The proof will fail if another pubkey is provided. problem: number of the problem proof: the 'proof.bin' generated by euler-client pubkey: the pubkey of the user, as used when generating 'proof.bin'
function submit( uint32 problem, bytes proof, uint256 pubkey) public view override { address addr = problem_address( problem ); EulerProblem( addr ).submit }
13,107,316
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; // Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below). contract LiquidationWithdrawer { function withdrawLiquidation( address financialContractAddress, uint256 liquidationId, address sponsor ) public returns (FixedPoint.Unsigned memory) { return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor); } } interface IFinancialContract { function withdrawLiquidation(uint256 liquidationId, address sponsor) external returns (FixedPoint.Unsigned memory amountWithdrawn); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-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 Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length, ancillaryData: ancillaryData }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ 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; } } pragma solidity ^0.6.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))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("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: AGPL-3.0-only pragma solidity ^0.6.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the * upgrade process for Voting.sol. * @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only * the ones that need to be performed atomically. */ contract VotingUpgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; // Address to call setMigrated on the old voting contract. address public setMigratedAddress; /** * @notice Removes an address from the whitelist. * @param _governor the Governor contract address. * @param _existingVoting the current/existing Voting contract address. * @param _newVoting the new Voting deployment address. * @param _finder the Finder contract address. * @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to * old voting contract (used to claim rewards on others' behalf). Note: this address * can always be changed by the voters. */ constructor( address _governor, address _existingVoting, address _newVoting, address _finder, address _setMigratedAddress ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); setMigratedAddress = _setMigratedAddress; } /** * @notice Performs the atomic portion of the upgrade process. * @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and * returns ownership of the existing Voting contract and Finder back to the Governor. */ function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set the preset "migrated" address to allow this address to claim rewards on voters' behalf. // This also effectively shuts down the existing voting contract so new votes cannot be triggered. existingVoting.setMigrated(setMigratedAddress); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData); event PushedPrice( address indexed pusher, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } emit PushedPrice(msg.sender, identifier, time, ancillaryData, price); } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. * @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice, uint256 expirationTimestamp, address currency ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } emit ProposePrice( requester, proposer, identifier, timestamp, ancillaryData, proposedPrice, request.expirationTime, address(request.currency) ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; uint256 bond = request.bond; totalBond = bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); // Avoids stack too deep compilation error. { // Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it // proportionally more expensive to delay the resolution even if the proposer and disputer are the same // party. uint256 burnedBond = _computeBurnedBond(request); // The total fee is the burned bond and the final fee added together. uint256 totalFee = finalFee.add(burnedBond); if (totalFee > 0) { request.currency.safeIncreaseAllowance(address(store), totalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee)); } } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } emit DisputePrice( requester, request.proposer, disputer, identifier, timestamp, ancillaryData, request.proposedPrice ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; uint256 bond = request.bond; // Unburned portion of the loser's bond = 1 - burned bond. uint256 unburnedBond = bond.sub(_computeBurnedBond(request)); // Winner gets: // - Their bond back. // - The unburned portion of the loser's bond. // - Their final fee back. // - The request reward (if not already refunded -- if refunded, it will be set to 0). payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _computeBurnedBond(Request storage request) private view returns (uint256) { // burnedBond = floor(bond / 2) return request.bond.div(2); } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; // Implement collateralCurrency so that this contract simulates a financial contract whose collateral // token can be fetched by off-chain clients. IERC20 public collateralCurrency; // Manually set an expiration timestamp to simulate expiry price requests uint256 public expirationTimestamp; constructor(OptimisticOracle _optimisticOracle) public { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { // Set collateral currency to last requested currency: collateralCurrency = currency; currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function settleAndGetPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function setExpirationTimestamp(uint256 _expirationTimestamp) external { expirationTimestamp = _expirationTimestamp; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) { uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract. ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) = getOutstandingRegularFees(time); lastPaymentTime = time; // If there are no fees to pay then exit early. if (totalPaid.isEqual(0)) { return totalPaid; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more * than the total collateral within the contract then the totalPaid returned is full contract collateral amount. * @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. * @return regularFee outstanding unpaid regular fee. * @return latePenalty outstanding unpaid late fee for being late in previous fee payments. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). */ function getOutstandingRegularFees(uint256 time) public view returns ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) { StoreInterface store = _getStore(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral or if fees were already paid during this block. if (collateralPool.isEqual(0) || lastPaymentTime == time) { return (regularFee, latePenalty, totalPaid); } (regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return (regularFee, latePenalty, totalPaid); } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Returns the user's collateral minus any pending fees that have yet to be subtracted. function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory) { (, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) = getOutstandingRegularFees(getCurrentTime()); if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral; // Calculate the total outstanding regular fee as a fraction of the total contract PFC. FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc()); // Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee. return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee)); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @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() external view returns (uint8); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) public { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) public Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, ancillaryData, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingAncillaryInterface) { return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Inspired by: * - https://github.com/pie-dao/vested-token-migration-app * - https://github.com/Uniswap/merkle-distributor * - https://github.com/balancer-labs/erc20-redeemable * * @title MerkleDistributor contract. * @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify * multiple Merkle roots distributions with customized reward currencies. * @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly. */ contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } } pragma solidity ^0.6.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier paysRegularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public paysRegularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPercentage).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _updateFundingRate() internal { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); _updateFundingRate(); // Update the funding rate if there is a resolved proposal. fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, fundingRate.rate, fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 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} to extend it to smaller types, by performing * all math on `uint256` 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 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); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPercentage; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() public { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPercentage.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPercentage.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final * fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: `payToLiquidator` should never be below zero since we enforce that // (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Post-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier * & if it is before expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is after contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return identifier; } else { return financialProductTransformedIdentifiers[msg.sender]; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title KPI Options Financial Product Library * @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract. * If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1. * Post-expiry, the collateral requirement is left as 1 and the price is left unchanged. */ contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable { /** * @notice Returns a transformed price for pre-expiry price requests. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with // each token backed 1:2 by collateral currency. Post-expiry, leave unchanged. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(2); } else { return oraclePrice; } } /** * @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled to a flat rate. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // Always return 1. return FixedPoint.fromUnscaledUint(1); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title CoveredCall Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If * ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by * (oraclePrice - strikePrice) / oraclePrice; * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH. * If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200). * If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400). * If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH. */ contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => FixedPoint.Unsigned) private financialProductStrikes; /** * @notice Enables any address to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the covered call to be applied to the financial product. * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool. * e) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the call option payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThanOrEqual(strike)) { return FixedPoint.fromUnscaledUint(0); } else { // Token expires to be worth the fraction of a collateral token that's in the money. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100). // Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always // true. return (oraclePrice.sub(strike)).div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the covered call payout structure. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // Always return 1 because option must be collateralized by 1 token. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/ExpandedERC20.sol"; contract TokenSender { function transferERC20( address tokenAddress, address recipientAddress, uint256 amount ) public returns (bool) { IERC20 token = IERC20(tokenAddress); token.transfer(recipientAddress, amount); return true; } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ 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 () internal { _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. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IDepositExecute.sol"; import "./IBridge.sol"; import "./IERCHandler.sol"; import "./IGenericHandler.sol"; /** @title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions. @author ChainSafe Systems. */ contract Bridge is Pausable, AccessControl { using SafeMath for uint256; uint8 public _chainID; uint256 public _relayerThreshold; uint256 public _totalRelayers; uint256 public _totalProposals; uint256 public _fee; uint256 public _expiry; enum Vote { No, Yes } enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled } struct Proposal { bytes32 _resourceID; bytes32 _dataHash; address[] _yesVotes; address[] _noVotes; ProposalStatus _status; uint256 _proposedBlock; } // destinationChainID => number of deposits mapping(uint8 => uint64) public _depositCounts; // resourceID => handler address mapping(bytes32 => address) public _resourceIDToHandlerAddress; // depositNonce => destinationChainID => bytes mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords; // destinationChainID + depositNonce => dataHash => Proposal mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals; // destinationChainID + depositNonce => dataHash => relayerAddress => bool mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal; event RelayerThresholdChanged(uint256 indexed newThreshold); event RelayerAdded(address indexed relayer); event RelayerRemoved(address indexed relayer); event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce); event ProposalEvent( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID, bytes32 dataHash ); event ProposalVote( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID ); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); modifier onlyAdmin() { _onlyAdmin(); _; } modifier onlyAdminOrRelayer() { _onlyAdminOrRelayer(); _; } modifier onlyRelayers() { _onlyRelayers(); _; } function _onlyAdminOrRelayer() private { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender), "sender is not relayer or admin" ); } function _onlyAdmin() private { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role"); } function _onlyRelayers() private { require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role"); } /** @notice Initializes Bridge, creates and grants {msg.sender} the admin role, creates and grants {initialRelayers} the relayer role. @param chainID ID of chain the Bridge contract exists on. @param initialRelayers Addresses that should be initially granted the relayer role. @param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed. */ constructor( uint8 chainID, address[] memory initialRelayers, uint256 initialRelayerThreshold, uint256 fee, uint256 expiry ) public { _chainID = chainID; _relayerThreshold = initialRelayerThreshold; _fee = fee; _expiry = expiry; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE); for (uint256 i; i < initialRelayers.length; i++) { grantRole(RELAYER_ROLE, initialRelayers[i]); _totalRelayers++; } } /** @notice Returns true if {relayer} has the relayer role. @param relayer Address to check. */ function isRelayer(address relayer) external view returns (bool) { return hasRole(RELAYER_ROLE, relayer); } /** @notice Removes admin role from {msg.sender} and grants it to {newAdmin}. @notice Only callable by an address that currently has the admin role. @param newAdmin Address that admin role will be granted to. */ function renounceAdmin(address newAdmin) external onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, newAdmin); renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** @notice Pauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminPauseTransfers() external onlyAdmin { _pause(); } /** @notice Unpauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminUnpauseTransfers() external onlyAdmin { _unpause(); } /** @notice Modifies the number of votes required for a proposal to be considered passed. @notice Only callable by an address that currently has the admin role. @param newThreshold Value {_relayerThreshold} will be changed to. @notice Emits {RelayerThresholdChanged} event. */ function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin { _relayerThreshold = newThreshold; emit RelayerThresholdChanged(newThreshold); } /** @notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be added. @notice Emits {RelayerAdded} event. */ function adminAddRelayer(address relayerAddress) external onlyAdmin { require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!"); grantRole(RELAYER_ROLE, relayerAddress); emit RelayerAdded(relayerAddress); _totalRelayers++; } /** @notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be removed. @notice Emits {RelayerRemoved} event. */ function adminRemoveRelayer(address relayerAddress) external onlyAdmin { require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!"); revokeRole(RELAYER_ROLE, relayerAddress); emit RelayerRemoved(relayerAddress); _totalRelayers--; } /** @notice Sets a new resource for handler contracts that use the IERCHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetResource( address handlerAddress, bytes32 resourceID, address tokenAddress ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IERCHandler handler = IERCHandler(handlerAddress); handler.setResource(resourceID, tokenAddress); } /** @notice Sets a new resource for handler contracts that use the IGenericHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetGenericResource( address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IGenericHandler handler = IGenericHandler(handlerAddress); handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice Sets a resource as burnable for handler contracts that use the IERCHandler interface. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.setBurnable(tokenAddress); } /** @notice Returns a proposal. @param originChainID Chain ID deposit originated from. @param depositNonce ID of proposal generated by proposal's origin Bridge contract. @param dataHash Hash of data to be provided when deposit proposal is executed. @return Proposal which consists of: - _dataHash Hash of data to be provided when deposit proposal is executed. - _yesVotes Number of votes in favor of proposal. - _noVotes Number of votes against proposal. - _status Current status of proposal. */ function getProposal( uint8 originChainID, uint64 depositNonce, bytes32 dataHash ) external view returns (Proposal memory) { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID); return _proposals[nonceAndID][dataHash]; } /** @notice Changes deposit fee. @notice Only callable by admin. @param newFee Value {_fee} will be updated to. */ function adminChangeFee(uint256 newFee) external onlyAdmin { require(_fee != newFee, "Current fee is equal to new fee"); _fee = newFee; } /** @notice Used to manually withdraw funds from ERC safes. @param handlerAddress Address of handler to withdraw from. @param tokenAddress Address of token to withdraw. @param recipient Address to withdraw tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw. */ function adminWithdraw( address handlerAddress, address tokenAddress, address recipient, uint256 amountOrTokenID ) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.withdraw(tokenAddress, recipient, amountOrTokenID); } /** @notice Initiates a transfer using a specified handler contract. @notice Only callable when Bridge is not paused. @param destinationChainID ID of chain deposit will be bridged to. @param resourceID ResourceID used to find address of handler to be used for deposit. @param data Additional data to be passed to specified handler. @notice Emits {Deposit} event. */ function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external payable whenNotPaused { require(msg.value == _fee, "Incorrect fee supplied"); address handler = _resourceIDToHandlerAddress[resourceID]; require(handler != address(0), "resourceID not mapped to handler"); uint64 depositNonce = ++_depositCounts[destinationChainID]; _depositRecords[depositNonce][destinationChainID] = data; IDepositExecute depositHandler = IDepositExecute(handler); depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data); emit Deposit(destinationChainID, resourceID, depositNonce); } /** @notice When called, {msg.sender} will be marked as voting in favor of proposal. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data provided when deposit was made. @notice Proposal must not have already been passed or executed. @notice {msg.sender} must not have already voted on proposal. @notice Emits {ProposalEvent} event with status indicating the proposal status. @notice Emits {ProposalVote} event. */ function voteProposal( uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes32 dataHash ) external onlyRelayers whenNotPaused { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID"); require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled"); require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted"); if (uint256(proposal._status) == 0) { ++_totalProposals; _proposals[nonceAndID][dataHash] = Proposal({ _resourceID: resourceID, _dataHash: dataHash, _yesVotes: new address[](1), _noVotes: new address[](0), _status: ProposalStatus.Active, _proposedBlock: block.number }); proposal._yesVotes[0] = msg.sender; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash); } else { if (block.number.sub(proposal._proposedBlock) > _expiry) { // if the number of blocks that has passed since this proposal was // submitted exceeds the expiry threshold set, cancel the proposal proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash); } else { require(dataHash == proposal._dataHash, "datahash mismatch"); proposal._yesVotes.push(msg.sender); } } if (proposal._status != ProposalStatus.Cancelled) { _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true; emit ProposalVote(chainID, depositNonce, proposal._status, resourceID); // If _depositThreshold is set to 1, then auto finalize // or if _relayerThreshold has been exceeded if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) { proposal._status = ProposalStatus.Passed; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash); } } } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data originally provided when deposit was made. @notice Proposal must be past expiry threshold. @notice Emits {ProposalEvent} event with status {Cancelled}. */ function cancelProposal( uint8 chainID, uint64 depositNonce, bytes32 dataHash ) public onlyAdminOrRelayer { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled"); require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold"); proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash); } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param resourceID ResourceID to be used when making deposits. @param depositNonce ID of deposited generated by origin Bridge contract. @param data Data originally provided when deposit was made. @notice Proposal must have Passed status. @notice Hash of {data} must equal proposal's {dataHash}. @notice Emits {ProposalEvent} event with status {Executed}. */ function executeProposal( uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID ) external onlyRelayers whenNotPaused { address handler = _resourceIDToHandlerAddress[resourceID]; uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); bytes32 dataHash = keccak256(abi.encodePacked(handler, data)); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Inactive, "proposal is not active"); require(proposal._status == ProposalStatus.Passed, "proposal already transferred"); require(dataHash == proposal._dataHash, "data doesn't match datahash"); proposal._status = ProposalStatus.Executed; IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]); depositHandler.executeProposal(proposal._resourceID, data); emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash); } /** @notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1. This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0. @param addrs Array of addresses to transfer {amounts} to. @param amounts Array of amonuts to transfer to {addrs}. */ function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin { for (uint256 i = 0; i < addrs.length; i++) { addrs[i].transfer(amounts[i]); } } } pragma solidity ^0.6.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, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } pragma solidity ^0.6.0; /** @title Interface for handler contracts that support deposits and deposit executions. @author ChainSafe Systems. */ interface IDepositExecute { /** @notice It is intended that deposit are made using the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; /** @notice It is intended that proposals are executed by the Bridge contract. @param data Consists of additional data needed for a specific deposit execution. */ function executeProposal(bytes32 resourceID, bytes calldata data) external; } pragma solidity ^0.6.0; /** @title Interface for Bridge contract. @author ChainSafe Systems. */ interface IBridge { /** @notice Exposing getter for {_chainID} instead of forcing the use of call. @return uint8 The {_chainID} that is currently set for the Bridge contract. */ function _chainID() external returns (uint8); } pragma solidity ^0.6.0; /** @title Interface to be used with handlers that support ERC20s and ERC721s. @author ChainSafe Systems. */ interface IERCHandler { /** @notice Correlates {resourceID} with {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external; /** @notice Marks {contractAddress} as mintable/burnable. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external; /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external; } pragma solidity ^0.6.0; /** @title Interface for handler that handles generic deposits and deposit executions. @author ChainSafe Systems. */ interface IGenericHandler { /** @notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external; } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./IGenericHandler.sol"; /** @title Handles generic deposits and deposit executions. @author ChainSafe Systems. @notice This contract is intended to be used with the Bridge contract. */ contract GenericHandler is IGenericHandler { address public _bridgeAddress; struct DepositRecord { uint8 _destinationChainID; address _depositer; bytes32 _resourceID; bytes _metaData; } // depositNonce => Deposit Record mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords; // resourceID => contract address mapping(bytes32 => address) public _resourceIDToContractAddress; // contract address => resourceID mapping(address => bytes32) public _contractAddressToResourceID; // contract address => deposit function signature mapping(address => bytes4) public _contractAddressToDepositFunctionSignature; // contract address => execute proposal function signature mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature; // token contract address => is whitelisted mapping(address => bool) public _contractWhitelist; modifier onlyBridge() { _onlyBridge(); _; } function _onlyBridge() private { require(msg.sender == _bridgeAddress, "sender must be bridge contract"); } /** @param bridgeAddress Contract address of previously deployed Bridge. @param initialResourceIDs Resource IDs used to identify a specific contract address. These are the Resource IDs this contract will initially support. @param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be called to perform deposit and execution calls. @param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {deposit} @param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {executeProposal} @dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures}, and {initialExecuteFunctionSignatures} must all have the same length. Also, values must be ordered in the way that that index x of any mentioned array must be intended for value x of any other array, e.g. {initialContractAddresses}[0] is the intended address for {initialDepositFunctionSignatures}[0]. */ constructor( address bridgeAddress, bytes32[] memory initialResourceIDs, address[] memory initialContractAddresses, bytes4[] memory initialDepositFunctionSignatures, bytes4[] memory initialExecuteFunctionSignatures ) public { require( initialResourceIDs.length == initialContractAddresses.length, "initialResourceIDs and initialContractAddresses len mismatch" ); require( initialContractAddresses.length == initialDepositFunctionSignatures.length, "provided contract addresses and function signatures len mismatch" ); require( initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length, "provided deposit and execute function signatures len mismatch" ); _bridgeAddress = bridgeAddress; for (uint256 i = 0; i < initialResourceIDs.length; i++) { _setResource( initialResourceIDs[i], initialContractAddresses[i], initialDepositFunctionSignatures[i], initialExecuteFunctionSignatures[i] ); } } /** @param depositNonce This ID will have been generated by the Bridge contract. @param destId ID of chain deposit will be bridged to. @return DepositRecord which consists of: - _destinationChainID ChainID deposited tokens are intended to end up on. - _resourceID ResourceID used when {deposit} was executed. - _depositer Address that initially called {deposit} in the Bridge contract. - _metaData Data to be passed to method executed in corresponding {resourceID} contract. */ function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) { return _depositRecords[destId][depositNonce]; } /** @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, {_contractAddressToDepositFunctionSignature} with {depositFunctionSig}, {_contractAddressToExecuteFunctionSignature} with {executeFunctionSig}, and {_contractWhitelist} to true for {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external override onlyBridge { _setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice A deposit is initiatied by making a deposit in the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 64 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external onlyBridge { bytes32 lenMetadata; bytes memory metadata; assembly { // Load length of metadata from data + 64 lenMetadata := calldataload(0xC4) // Load free memory pointer metadata := mload(0x40) mstore(0x40, add(0x20, add(metadata, lenMetadata))) // func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) + // bytes length (32) + resourceId (32) + length (32) = 0xC4 calldatacopy( metadata, // copy to metadata 0xC4, // copy from calldata after metadata length declaration @0xC4 sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up)) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metadata); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } _depositRecords[destinationChainID][depositNonce] = DepositRecord( destinationChainID, depositer, resourceID, metadata ); } /** @notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract. @param data Consists of {resourceID}, {lenMetaData}, and {metaData}. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 32 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge { bytes memory metaData; assembly { // metadata has variable length // load free memory pointer to store metadata metaData := mload(0x40) // first 32 bytes of variable length in storage refer to length let lenMeta := calldataload(0x64) mstore(0x40, add(0x60, add(metaData, lenMeta))) // in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params calldatacopy( metaData, // copy to metaData 0x64, // copy from calldata after data length declaration at 0x64 sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metaData); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } } function _setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) internal { _resourceIDToContractAddress[resourceID] = contractAddress; _contractAddressToResourceID[contractAddress] = resourceID; _contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig; _contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig; _contractWhitelist[contractAddress] = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/lib/contracts/libraries/FullMath.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; /** * @title UniswapBroker * @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual * synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically * swap and move a uniswap market. */ contract UniswapBroker { using SafeMath for uint256; /** * @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as * possible to the truePrice. * @dev True price is expressed in the ratio of token A to token B. * @dev The caller must approve this contract to spend whichever token is intended to be swapped. * @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param uniswapFactory address of the uniswap factory used to fetch current pair reserves. * @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure * out which tokens need to be exchanged to move the market to the desired "true" price. * @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price * and the 1st value is the the denominator of the true price. * @param maxSpendTokens array of unit to represent the max to spend in the two tokens. * @param to recipient of the trade proceeds. * @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert. */ function swapToPrice( bool tradingAsEOA, address uniswapRouter, address uniswapFactory, address[2] memory swappedTokens, uint256[2] memory truePriceTokens, uint256[2] memory maxSpendTokens, address to, uint256 deadline ) public { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); // true price is expressed as a ratio, so both values must be non-zero require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE"); // caller can specify 0 for either if they wish to swap in only one direction, but not both require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND"); bool aToB; uint256 amountIn; { (uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]); (aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB); } require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN"); // spend up to the allowance of the token in uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1]; if (amountIn > maxSpend) { amountIn = maxSpend; } address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1]; address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0]; TransferHelper.safeApprove(tokenIn, address(router), amountIn); if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; router.swapExactTokensForTokens( amountIn, 0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests. path, to, deadline ); } /** * @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the * uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move * the pool price to be equal to the true price. * @dev Note that this method uses the Babylonian square root method which has a small margin of error which will * result in a small over or under estimation on the size of the trade needed. * @param truePriceTokenA the nominator of the true price. * @param truePriceTokenB the denominator of the true price. * @param reserveA number of token A in the pair reserves * @param reserveB number of token B in the pair reserves */ // function computeTradeToMoveMarket( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) public pure returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); // The trade ∆a of token a required to move the market to some desired price P' from the current price P can be // found with ∆a=(kP')^1/2-Ra. uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant, aToB ? truePriceTokenA : truePriceTokenB, aToB ? truePriceTokenB : truePriceTokenA ) ); uint256 rightSide = (aToB ? reserveA : reserveB); if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price back to the true price. amountIn = leftSide.sub(rightSide); } // The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol // We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound // to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so // unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant // handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker // are simply moved here to maintain truffle support. function getReserves( address factory, address tokenA, address tokenB ) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } } 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: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } 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); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title ReserveCurrencyLiquidator * @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of * financial contracts. Is assumed to be called by a DSProxy which holds reserve currency. */ contract ReserveCurrencyLiquidator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /** * @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to * liquidate a position within one transaction. * @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending * liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has * passed liveness. At this point the position can be manually unwound. * @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted. * These existing tokens will be used first before any swaps or mints are done. * @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough * collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param financialContract address of the financial contract on which the liquidation is occurring. * @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy. * @param liquidatedSponsor address of the sponsor to be liquidated. * @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage. * @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt. * @param deadline abort the trade and liquidation if the transaction is mined after this timestamp. **/ function swapMintLiquidate( address uniswapRouter, address financialContract, address reserveCurrency, address liquidatedSponsor, FixedPoint.Unsigned calldata maxReserveTokenSpent, FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) public { IFinancialContract fc = IFinancialContract(financialContract); // 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already // has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall). FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc)); // 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics. FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding()); FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr); // 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any // collateral needed to mint the token short fall. FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall); // 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this // will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0. FixedPoint.Unsigned memory collateralToBePurchased = subOrZero(totalCollateralRequired, getCollateralBalance(fc)); // 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall. // Note the path assumes a direct route from the reserve currency to the collateral currency. if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); address[] memory path = new address[](2); path[0] = reserveCurrency; path[1] = fc.collateralCurrency(); TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue); router.swapTokensForExactTokens( collateralToBePurchased.rawValue, maxReserveTokenSpent.rawValue, path, address(this), deadline ); } // 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve // or not enough collateral in the contract) the script should try to liquidate as much as it can regardless. // Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall // as the maximum tokens that could be liquidated at the current GCR. if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) { totalCollateralRequired = getCollateralBalance(fc); collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc)); tokenShortfall = collateralToMintShortfall.divCeil(gcr); } // 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR. // If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral // currency as this is needed to pay the final fee in the liquidation tx. TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue); if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall); // The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full // token token balance at this point if there was a shortfall. FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate; if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc); // 6. Liquidate position with newly minted synthetics. TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue); fc.createLiquidation( liquidatedSponsor, minCollateralPerTokenLiquidated, maxCollateralPerTokenLiquidated, liquidatableTokens, deadline ); } // Helper method to work around subtraction overflow in the case of: a - b with b > a. function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b) internal pure returns (FixedPoint.Unsigned memory) { return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b); } // Helper method to return the current final fee for a given financial contract instance. function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency()); } // Helper method to return the collateral balance of this contract. function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this))); } // Helper method to return the synthetic balance of this contract. function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this))); } } // Define some simple interfaces for dealing with UMA contracts. interface IFinancialContract { struct PositionData { FixedPoint.Unsigned tokensOutstanding; uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; FixedPoint.Unsigned rawCollateral; uint256 transferPositionRequestPassTimestamp; } function positions(address sponsor) external returns (PositionData memory); function collateralCurrency() external returns (address); function tokenCurrency() external returns (address); function finder() external returns (address); function pfc() external returns (FixedPoint.Unsigned memory); function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory); function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external; function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ); } interface IStore { function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory); } interface IFinder { function getImplementationAddress(bytes32 interfaceName) external view returns (address); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; // Simple contract used to redeem tokens using a DSProxy from an emp. contract TokenRedeemer { function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens) public returns (FixedPoint.Unsigned memory) { IFinancialContract fc = IFinancialContract(financialContractAddress); TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue); return fc.redeem(numTokens); } } interface IFinancialContract { function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn); function tokenCurrency() external returns (address); } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/VaultInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Mock for yearn-style vaults for use in tests. */ contract VaultMock is VaultInterface { IERC20 public override token; uint256 private pricePerFullShare = 0; constructor(IERC20 _token) public { token = _token; } function getPricePerFullShare() external view override returns (uint256) { return pricePerFullShare; } function setPricePerFullShare(uint256 _pricePerFullShare) external { pricePerFullShare = _pricePerFullShare; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Interface for Yearn-style vaults. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract VaultInterface { // Return the underlying token. function token() external view virtual returns (IERC20); // Gets the number of return tokens that a "share" of this vault is worth. function getPricePerFullShare() external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) public { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Simple Perpetual Mock to serve trivial functions */ contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return now; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
Transfers `collateralAmount` of `collateralCurrency` into the caller's position. Increases the collateralization level of a position after creation. This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. collateralAmount total amount of collateral tokens to be sent to the sponsor's position./ This is just a thin wrapper over depositTo that specified the sender as the sponsor.
function deposit(FixedPoint.Unsigned memory collateralAmount) public { depositTo(msg.sender, collateralAmount); }
99,481
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol"; import "../MiraiCore.sol"; /** * @title MiraiOwnership * @notice MiraiOwnership is the entry point for interacting with the Mirai backend **/ contract MiraiOwnership is ERC721Token { /** * @notice Issued is emitted when a new POP is issued */ event POPIssued( uint256 tokenId, address purchaser, string productId, uint256 issuedTime ); MiraiCore core; constructor (string _name, string _symbol, address _coreAddress) public ERC721Token(_name, _symbol){ core = MiraiCore(_coreAddress); } /** * @notice Makes a purchase of a product, issuing a proof of purchase token * @param _uri the string of the productId to purchase *tokenId <-> bookId relationship kept track in tokenURI * @param owner the owner of the product - who to send the ETH to */ function buyPOP(string _uri, address owner) public payable { uint256 newTokenId = super.totalSupply(); super._mint(msg.sender, newTokenId); super._setTokenURI(newTokenId, _uri); emit POPIssued(newTokenId, msg.sender, _uri, block.timestamp); owner.transfer(msg.value); core.incrementNumberSold(_uri); } /** * @notice retrieves array of owned tokensIds. Uses inhereted mapping ownedTokens * @param _owner the address to find owned tokenIds */ function getTokensByOwner(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } }
Makes a purchase of a product, issuing a proof of purchase token _uri the string of the productId to purchasetokenId <-> bookId relationship kept track in tokenURI owner the owner of the product - who to send the ETH to/
function buyPOP(string _uri, address owner) public payable { uint256 newTokenId = super.totalSupply(); super._mint(msg.sender, newTokenId); super._setTokenURI(newTokenId, _uri); emit POPIssued(newTokenId, msg.sender, _uri, block.timestamp); owner.transfer(msg.value); core.incrementNumberSold(_uri); }
12,741,833
// File: contracts/lib/LibMath.sol pragma solidity ^0.5.7; contract LibMath { // Copied from openzeppelin 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 Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ 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); } // Modified from openzeppelin SafeMath /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } // Copied from 0x LibMath /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function safeGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); require( !isRoundingErrorFloor( numerator, denominator, target ), "ROUNDING_ERROR" ); partialAmount = div( mul(numerator, target), denominator ); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function safeGetPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); require( !isRoundingErrorCeil( numerator, denominator, target ), "ROUNDING_ERROR" ); partialAmount = div( add( mul(numerator, target), sub(denominator, 1) ), denominator ); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function getPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); partialAmount = div( mul(numerator, target), denominator ); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function getPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); partialAmount = div( add( mul(numerator, target), sub(denominator, 1) ), denominator ); return partialAmount; } /// @dev Checks if rounding error >= 0.1% when rounding down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { require( denominator > 0, "DIVISION_BY_ZERO" ); // The absolute rounding error is the difference between the rounded // value and the ideal value. The relative rounding error is the // absolute rounding error divided by the absolute value of the // ideal value. This is undefined when the ideal value is zero. // // The ideal value is `numerator * target / denominator`. // Let's call `numerator * target % denominator` the remainder. // The absolute error is `remainder / denominator`. // // When the ideal value is zero, we require the absolute error to // be zero. Fortunately, this is always the case. The ideal value is // zero iff `numerator == 0` and/or `target == 0`. In this case the // remainder and absolute error are also zero. if (target == 0 || numerator == 0) { return false; } // Otherwise, we want the relative rounding error to be strictly // less than 0.1%. // The relative error is `remainder / (numerator * target)`. // We want the relative error less than 1 / 1000: // remainder / (numerator * denominator) < 1 / 1000 // or equivalently: // 1000 * remainder < numerator * target // so we have a rounding error iff: // 1000 * remainder >= numerator * target uint256 remainder = mulmod( target, numerator, denominator ); isError = mul(1000, remainder) >= mul(numerator, target); return isError; } /// @dev Checks if rounding error >= 0.1% when rounding up. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { require( denominator > 0, "DIVISION_BY_ZERO" ); // See the comments in `isRoundingError`. if (target == 0 || numerator == 0) { // When either is zero, the ideal value and rounded value are zero // and there is no rounding error. (Although the relative error // is undefined.) return false; } // Compute remainder as before uint256 remainder = mulmod( target, numerator, denominator ); remainder = sub(denominator, remainder) % denominator; isError = mul(1000, remainder) >= mul(numerator, target); return isError; } } // File: contracts/lib/Ownable.sol pragma solidity ^0.5.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/lib/ReentrancyGuard.sol pragma solidity ^0.5.0; /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } // File: contracts/bank/IBank.sol pragma solidity ^0.5.7; /// Bank Interface. interface IBank { /// Modifies authorization of an address. Only contract owner can call this function. /// @param target Address to authorize / deauthorize. /// @param allowed Whether the target address is authorized. function authorize(address target, bool allowed) external; /// Modifies user approvals of an address. /// @param target Address to approve / unapprove. /// @param allowed Whether the target address is user approved. function userApprove(address target, bool allowed) external; /// Batch modifies user approvals. /// @param targetList Array of addresses to approve / unapprove. /// @param allowedList Array of booleans indicating whether the target address is user approved. function batchUserApprove(address[] calldata targetList, bool[] calldata allowedList) external; /// Gets all authorized addresses. /// @return Array of authorized addresses. function getAuthorizedAddresses() external view returns (address[] memory); /// Gets all user approved addresses. /// @return Array of user approved addresses. function getUserApprovedAddresses() external view returns (address[] memory); /// Checks whether the user has enough deposit. /// @param token Token address. /// @param user User address. /// @param amount Token amount. /// @param data Additional token data (e.g. tokenId for ERC721). /// @return Whether the user has enough deposit. function hasDeposit(address token, address user, uint256 amount, bytes calldata data) external view returns (bool); /// Checks token balance available to use (including user deposit amount + user approved allowance amount). /// @param token Token address. /// @param user User address. /// @param data Additional token data (e.g. tokenId for ERC721). /// @return Token amount available. function getAvailable(address token, address user, bytes calldata data) external view returns (uint256); /// Gets balance of user's deposit. /// @param token Token address. /// @param user User address. /// @return Token deposit amount. function balanceOf(address token, address user) external view returns (uint256); /// Deposits token from user wallet to bank. /// @param token Token address. /// @param user User address (allows third-party give tokens to any users). /// @param amount Token amount. /// @param data Additional token data (e.g. tokenId for ERC721). function deposit(address token, address user, uint256 amount, bytes calldata data) external payable; /// Withdraws token from bank to user wallet. /// @param token Token address. /// @param amount Token amount. /// @param data Additional token data (e.g. tokenId for ERC721). function withdraw(address token, uint256 amount, bytes calldata data) external; /// Transfers token from one address to another address. /// Only caller who are double-approved by both bank owner and token owner can invoke this function. /// @param token Token address. /// @param from The current token owner address. /// @param to The new token owner address. /// @param amount Token amount. /// @param data Additional token data (e.g. tokenId for ERC721). /// @param fromDeposit True if use fund from bank deposit. False if use fund from user wallet. /// @param toDeposit True if deposit fund to bank deposit. False if send fund to user wallet. function transferFrom( address token, address from, address to, uint256 amount, bytes calldata data, bool fromDeposit, bool toDeposit ) external; } // File: contracts/router/IExchangeHandler.sol pragma solidity ^0.5.7; /// Interface of exchange handler. interface IExchangeHandler { /// Gets maximum available amount can be spent on order (fee not included). /// @param data General order data. /// @return availableToFill Amount can be spent on order. /// @return feePercentage Fee percentage of order. function getAvailableToFill( bytes calldata data ) external view returns (uint256 availableToFill, uint256 feePercentage); /// Fills an order on the target exchange. /// NOTE: The required funds must be transferred to this contract in the same transaction of calling this function. /// @param data General order data. /// @param takerAmountToFill Taker token amount to spend on order (fee not included). /// @return makerAmountReceived Amount received from trade. function fillOrder( bytes calldata data, uint256 takerAmountToFill ) external payable returns (uint256 makerAmountReceived); } // File: contracts/router/RouterCommon.sol pragma solidity ^0.5.7; contract RouterCommon { struct GeneralOrder { address handler; address makerToken; address takerToken; uint256 makerAmount; uint256 takerAmount; bytes data; } struct FillResults { uint256 makerAmountReceived; uint256 takerAmountSpentOnOrder; uint256 takerAmountSpentOnFee; } } // File: contracts/router/ExchangeRouter.sol pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; // Interface of ERC20 approve function. interface IERC20 { function approve(address spender, uint256 value) external returns (bool); } /// Router contract to support orders from different decentralized exchanges. contract ExchangeRouter is Ownable, ReentrancyGuard, LibMath { IBank public bank; mapping(address => bool) public handlerWhitelist; event Handler(address handler, bool allowed); event FillOrder( bytes orderData, uint256 makerAmountReceived, uint256 takerAmountSpentOnOrder, uint256 takerAmountSpentOnFee ); constructor( address _bank ) public { bank = IBank(_bank); } /// Fallback function to receive ETH. function() external payable {} /// Sets a handler. Only contract owner can call this function. /// @param handler Handler address. /// @param allowed allowed Whether the handler address is trusted. function setHandler( address handler, bool allowed ) external onlyOwner { handlerWhitelist[handler] = allowed; emit Handler(handler, allowed); } /// Fills an order. /// @param order General order object. /// @param takerAmountToFill Taker token amount to spend on order. /// @param allowInsufficient Whether insufficient order remaining is allowed to fill. /// @return results Amounts paid and received. function fillOrder( RouterCommon.GeneralOrder memory order, uint256 takerAmountToFill, bool allowInsufficient ) public nonReentrant returns (RouterCommon.FillResults memory results) { results = fillOrderInternal( order, takerAmountToFill, allowInsufficient ); } /// Fills multiple orders by batch. /// @param orderList Array of general order objects. /// @param takerAmountToFillList Array of taker token amounts to spend on order. /// @param allowInsufficientList Array of booleans that whether insufficient order remaining is allowed to fill. function fillOrders( RouterCommon.GeneralOrder[] memory orderList, uint256[] memory takerAmountToFillList, bool[] memory allowInsufficientList ) public nonReentrant { for (uint256 i = 0; i < orderList.length; i++) { fillOrderInternal( orderList[i], takerAmountToFillList[i], allowInsufficientList[i] ); } } /// Given a list of orders, fill them in sequence until total taker amount is reached. /// NOTE: All orders should be in the same token pair. /// @param orderList Array of general order objects. /// @param totalTakerAmountToFill Stop filling when the total taker amount is reached. /// @return totalFillResults Total amounts paid and received. function marketTakerOrders( RouterCommon.GeneralOrder[] memory orderList, uint256 totalTakerAmountToFill ) public returns (RouterCommon.FillResults memory totalFillResults) { for (uint256 i = 0; i < orderList.length; i++) { RouterCommon.FillResults memory singleFillResults = fillOrderInternal( orderList[i], sub(totalTakerAmountToFill, totalFillResults.takerAmountSpentOnOrder), true ); addFillResults(totalFillResults, singleFillResults); if (totalFillResults.takerAmountSpentOnOrder >= totalTakerAmountToFill) { break; } } return totalFillResults; } /// Given a list of orders, fill them in sequence until total maker amount is reached. /// NOTE: All orders should be in the same token pair. /// @param orderList Array of general order objects. /// @param totalMakerAmountToFill Stop filling when the total maker amount is reached. /// @return totalFillResults Total amounts paid and received. function marketMakerOrders( RouterCommon.GeneralOrder[] memory orderList, uint256 totalMakerAmountToFill ) public returns (RouterCommon.FillResults memory totalFillResults) { for (uint256 i = 0; i < orderList.length; i++) { RouterCommon.FillResults memory singleFillResults = fillOrderInternal( orderList[i], getPartialAmountFloor( orderList[i].takerAmount, orderList[i].makerAmount, sub(totalMakerAmountToFill, totalFillResults.makerAmountReceived) ), true ); addFillResults(totalFillResults, singleFillResults); if (totalFillResults.makerAmountReceived >= totalMakerAmountToFill) { break; } } return totalFillResults; } /// Fills an order. /// @param order General order object. /// @param takerAmountToFill Taker token amount to spend on order. /// @param allowInsufficient Whether insufficient order remaining is allowed to fill. /// @return results Amounts paid and received. function fillOrderInternal( RouterCommon.GeneralOrder memory order, uint256 takerAmountToFill, bool allowInsufficient ) internal returns (RouterCommon.FillResults memory results) { // Check if the handler is trusted. require(handlerWhitelist[order.handler], "HANDLER_IN_WHITELIST_REQUIRED"); // Check order's availability. (uint256 availableToFill, uint256 feePercentage) = IExchangeHandler(order.handler).getAvailableToFill(order.data); if (allowInsufficient) { results.takerAmountSpentOnOrder = min(takerAmountToFill, availableToFill); } else { require(takerAmountToFill <= availableToFill, "INSUFFICIENT_ORDER_REMAINING"); results.takerAmountSpentOnOrder = takerAmountToFill; } results.takerAmountSpentOnFee = mul(results.takerAmountSpentOnOrder, feePercentage) / (1 ether); if (results.takerAmountSpentOnOrder > 0) { // Transfer funds from bank deposit to corresponding handler. bank.transferFrom( order.takerToken, msg.sender, order.handler, add(results.takerAmountSpentOnOrder, results.takerAmountSpentOnFee), "", true, false ); // Fill the order via handler. results.makerAmountReceived = IExchangeHandler(order.handler).fillOrder( order.data, results.takerAmountSpentOnOrder ); if (results.makerAmountReceived > 0) { if (order.makerToken == address(0)) { bank.deposit.value(results.makerAmountReceived)( address(0), msg.sender, results.makerAmountReceived, "" ); } else { require(IERC20(order.makerToken).approve(address(bank), results.makerAmountReceived)); bank.deposit( order.makerToken, msg.sender, results.makerAmountReceived, "" ); } } emit FillOrder( order.data, results.makerAmountReceived, results.takerAmountSpentOnOrder, results.takerAmountSpentOnFee ); } } /// @dev Adds properties of a single FillResults to total FillResults. /// @param totalFillResults Fill results instance that will be added onto. /// @param singleFillResults Fill results instance that will be added to totalFillResults. function addFillResults( RouterCommon.FillResults memory totalFillResults, RouterCommon.FillResults memory singleFillResults ) internal pure { totalFillResults.makerAmountReceived = add(totalFillResults.makerAmountReceived, singleFillResults.makerAmountReceived); totalFillResults.takerAmountSpentOnOrder = add(totalFillResults.takerAmountSpentOnOrder, singleFillResults.takerAmountSpentOnOrder); totalFillResults.takerAmountSpentOnFee = add(totalFillResults.takerAmountSpentOnFee, singleFillResults.takerAmountSpentOnFee); } }
Fills an order. order General order object. takerAmountToFill Taker token amount to spend on order. allowInsufficient Whether insufficient order remaining is allowed to fill. return results Amounts paid and received.
function fillOrder( RouterCommon.GeneralOrder memory order, uint256 takerAmountToFill, bool allowInsufficient ) public nonReentrant returns (RouterCommon.FillResults memory results) { results = fillOrderInternal( order, takerAmountToFill, allowInsufficient ); }
12,621,075
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; import "./provableAPI.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; //import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.2.0/contracts/access/Ownable.sol"; //import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.2.0/contracts/math/SafeMath.sol"; /// @title A blackjack game /// @author Clark Henry /// @notice This contract has known security risks and should not be deployed in production contract Blackjack is Ownable, usingProvable { using SafeMath for *; /// @dev Type declarations enum Stage { Bet, PlayHand, PlaySplitHand, ConcludeHands } struct Game { uint256 id; uint64 startTime; uint64 round; Stage stage; Player dealer; Player player; Player splitPlayer; } struct Player { uint256 bet; uint256 doubleDownBet; uint256 seed; uint8 score; uint256[] hand; } /// @dev State variables /// @dev Includes some circuit breakers /// @dev Update maxBet to be Kelly optimal uint256 constant NUMBER_OF_DECKS = 1; uint8[13] cardValues = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]; mapping(address => Game) games; string private randomCards; uint256 seed; uint256 maxBet; // used for bet (risk) optimization bool stopLoss; // used for circuit breaker uint8 lossCounter; uint8 lossLimit = 20; // consecutive losses /// @dev Events event StageChanged(uint256 gameId, uint64 round, Stage newStage); event NewRound(uint256 gameId, uint64 round, address player, uint256 bet); event CardDrawn(uint256 gameId, uint64 round, uint8 cardValue, uint8 score); event Result(uint256 gameId, uint64 round, uint256 payout, uint8 playerScore, uint8 dealerScore); event PlayerHand(uint256 gameId, uint256[] playerHand, uint256[] playerSplitHand); event LogNewWolframRandomDraw(string cards); event LogNewProvableQuery(string description); event Received(address, uint); /// @dev Functions /// @dev seed should not be based on timestamp. This is a security risk and placeholder for now constructor() public { seed = block.timestamp; } fallback() external {} receive() external payable { emit Received(msg.sender, msg.value); maxBet = SafeMath.div(address(this).balance, 200); } /// @dev [Module 10, Lesson 1] Action restriction on critical function /// @dev [Module 10, Lesson 1] Mortality /// @dev [Library used] Ownable library from OpenZeppelin is imported and used here. function kill() public onlyOwner() { selfdestruct(address(uint160(owner()))); } /// @dev [Module 10, Lesson 1] Circuit breakers implemented here modifier stopInEmergency() { require(!stopLoss, "Circuit breaker triggered"); _; } modifier atStage(Stage _stage) { require(games[msg.sender].stage == _stage, "Function cannot be called at this time."); _; } modifier eitherStage(Stage _stage1, Stage _stage2) { require(games[msg.sender].stage == _stage1 || games[msg.sender].stage == _stage2, "Function cannot be called at this time."); _; } /// @dev Need to implement card removal /// @dev seed should not be based on timestamp. This is a security risk and placeholder for now /// @param game The current game containing the player drawing a card /// @param player A player from a Blackjack game, holding a hand to draw card to function drawCard(Game storage game, Player storage player) private { uint64 _now = uint64(block.timestamp); uint256 card = ((player.seed * seed) + _now) % (NUMBER_OF_DECKS*52); player.seed = uint256(keccak256(abi.encodePacked(player.seed, card, _now))); seed = uint256(keccak256(abi.encodePacked(seed, card, _now))); player.hand.push(card); player.score = recalculate(player); emit CardDrawn(game.id, game.round, cardValues[uint8(card % 52 % 13)], player.score); } /// @dev Could be used for more complex check-reveal scheme for payable functions? /// @param game The current game which requires stage update function nextStage(Game storage game) internal { game.stage = Stage(uint(game.stage) + 1); if(game.stage == Stage.PlaySplitHand && game.splitPlayer.hand.length == 0) { game.stage = Stage(uint(game.stage) + 1); } emit StageChanged(game.id, game.round, game.stage); } /// @notice Start a new round of Blackjack with the transferred value as the original bet. /// @dev [Module 10, Lesson 1] Circuit breakers implemented here /// @dev seed should not be based on timestamp. This is a security risk and placeholder for now /// @dev Plan to split this into multiple functions such that placing bet is atomic before proceeding function newRound() public payable stopInEmergency { require(msg.value <= maxBet, "Bet must be less than the max bet."); uint256 _seed; uint64 _now = uint64(block.timestamp); uint256 id = uint256(keccak256(abi.encodePacked(block.number, _now, _seed))); seed += seed; Player memory dealer; Player memory player; Player memory splitPlayer; games[msg.sender] = Game(id, _now, 0, Stage.Bet, dealer, player, splitPlayer); Game storage game = games[msg.sender]; //reset(game); game.player.bet = msg.value; game.dealer.seed = ~_seed; game.player.seed = _seed; game.splitPlayer.seed = _seed; game.round++; emit NewRound(game.id, game.round, msg.sender, msg.value); dealCards(game); emit PlayerHand(game.id, game.player.hand, game.splitPlayer.hand); nextStage(game); } /// @dev Not sure this is optimized in terms of stage updates and call timing /// @param game The current game which requires stage reset function reset(Game storage game) internal { game.stage = Stage.Bet; emit StageChanged(game.id, game.round, game.stage); game.player.bet = 0; game.player.doubleDownBet = 0; game.splitPlayer.bet = 0; game.splitPlayer.doubleDownBet = 0; game.player.score = 0; delete game.player.hand; game.splitPlayer.score = 0; delete game.splitPlayer.hand; game.dealer.score = 0; delete game.dealer.hand; } /// @param player A player from a Blackjack game, holding a hand to calculate the score on /// @return score The Blackjack score for the player. function recalculate(Player storage player) private view returns (uint8 score) { uint8 numberOfAces = 0; for (uint8 i = 0; i < player.hand.length; i++) { uint8 card = (uint8) (player.hand[i] % 52 % 13); score += cardValues[card]; if (card == 0) numberOfAces++; } while (numberOfAces > 0 && score > 21) { score -= 10; numberOfAces--; } } /// @dev done only at start of hand /// @param game The current game which is starting function dealCards(Game storage game) private atStage(Stage.Bet) { drawCard(game, game.player); drawCard(game, game.dealer); drawCard(game, game.player); } /// @notice Split first two cards into two hands, drawing one additional card for each. An equivalent bet value is required. /// @dev not working correctly on last check - the require for bet size was reverting function split() public payable atStage(Stage.PlayHand) { Game storage game = games[msg.sender]; require(msg.value == game.player.bet, "Must match original bet to split"); require(game.player.hand.length == 2, "Can only split with two cards"); require(game.splitPlayer.hand.length == 0, "Can only split once"); require(cardValues[game.player.hand[0] % 13] == cardValues[game.player.hand[1] % 13], "First two cards must be same"); game.splitPlayer.hand.push(game.player.hand[1]); game.player.hand.pop(); drawCard(game, game.player); drawCard(game, game.splitPlayer); emit PlayerHand(game.id, game.player.hand, game.splitPlayer.hand); game.player.score = recalculate(game.player); game.splitPlayer.score = recalculate(game.splitPlayer); game.splitPlayer.bet = msg.value; } /// @notice Double down on first two cards, taking one additional card and standing, with an opportunity to double original bet. /// @dev is this vulnerable to OOG leaking drawn card info? /// @dev [Module 9, Lesson 3] Preventing integer overflow with SafeMath function doubleDown() public payable eitherStage(Stage.PlayHand, Stage.PlaySplitHand) { Game storage game = games[msg.sender]; require((game.player.hand.length == 2 && game.stage == Stage.PlayHand) || (game.splitPlayer.hand.length == 2 && game.stage == Stage.PlaySplitHand), "Can only double down with two cards"); require(msg.value <= game.player.bet, "Bet cannot be greater than original bet"); if (game.stage == Stage.PlayHand) { drawCard(game, game.player); game.player.doubleDownBet = SafeMath.add(game.player.doubleDownBet, msg.value); game.player.score = recalculate(game.player); } else if (game.stage == Stage.PlaySplitHand) { drawCard(game, game.splitPlayer); game.splitPlayer.doubleDownBet = SafeMath.add(game.splitPlayer.doubleDownBet, msg.value); game.splitPlayer.score = recalculate(game.splitPlayer); } nextStage(game); if(game.stage == Stage.ConcludeHands) { concludeGame(game); } } /// @notice Hit, taking one additional card on the current hand. /// @dev is this vulnerable to OOG leaking drawn card info? function hit() public eitherStage(Stage.PlayHand, Stage.PlaySplitHand) { Game storage game = games[msg.sender]; require(game.player.score < 21 && game.stage == Stage.PlayHand || (game.splitPlayer.score < 21 && game.stage == Stage.PlaySplitHand)); if (game.stage == Stage.PlayHand) { drawCard(game, game.player); game.player.score = recalculate(game.player); if (game.player.score >= 21) { nextStage(game); if (game.splitPlayer.hand.length == 0) { concludeGame(game); } } } else { drawCard(game, game.splitPlayer); game.splitPlayer.score = recalculate(game.splitPlayer); if (game.splitPlayer.score >= 21) { concludeGame(game); } } } /// @notice Standing, taking no more additional cards and concluding the current hand. /// @dev is this vulnerable to gas limit leaking drawn card info? function stand() public eitherStage(Stage.PlayHand, Stage.PlaySplitHand) { Game storage game = games[msg.sender]; if((game.stage == Stage.PlayHand && game.splitPlayer.hand.length == 0) || game.stage == Stage.PlaySplitHand ) { nextStage(game); concludeGame(game); } else { nextStage(game); } } /// @dev TODO: Change dealer rules from S17 to H17 /// @dev TODO: Properly handle when dealer has Blackjack (i.e., refund doubles and splits?) /// @param game The concluded Blackjack game /// @return bool Whether the dealer has Blackjack function drawDealerCards(Game storage game) private returns (bool) { if ( (game.player.score > 21 && game.splitPlayer.hand.length == 0) || (game.player.score > 21 && game.splitPlayer.score > 21) ) { drawCard(game, game.dealer); // just draw once if player has busted if (game.dealer.score == 21 && game.dealer.hand.length == 2) { return true; } } else { // Dealer must draw to 16 and stand on all 17's while (game.dealer.score < 17) { drawCard(game, game.dealer); if (game.dealer.score == 21 && game.dealer.hand.length == 2) { return true; } } } } /// @dev [Module 9, Lesson 3] Preventing integer overflow with SafeMath /// @dev [Module 10, Lesson 1] Circuit breakers implemented here /// @param game The game to conclude, paying out players if necessary function concludeGame(Game storage game) private stopInEmergency { uint payout = 0; bool dealerHasBJ = drawDealerCards(game); if (game.player.score <= 21) { payout = SafeMath.add(payout, calculatePayout(game, game.player, dealerHasBJ) ); } if (game.splitPlayer.score <= 21) { payout = SafeMath.add(payout, calculatePayout(game, game.splitPlayer, dealerHasBJ) ); } require(payout <= SafeMath.mul(game.player.bet, 8), "Dealer error - payout is too high."); // 2 hands * double down = 4 bets max if (payout != 0) { msg.sender.transfer(payout); lossCounter += 1; // increment circuit breaker } else { lossCounter = 0; // reset circuit breaker } // try circuit breaker if (lossCounter >= lossLimit) { stopLoss = true; } // update max bet maxBet = SafeMath.div(address(this).balance, 200); emit Result(game.id, game.round, payout, game.player.score, game.dealer.score); } /// @dev [Module 9, Lesson 3] Preventing integer overflow with SafeMath /// @dev TODO: Properly handle when dealer has Blackjack (i.e., refund doubles and splits?) /// @param game The concluded Blackjack game /// @param player A player from the game to calculate the payout for /// @return payout Amount of ether to transfer to player for winnings function calculatePayout(Game storage game, Player storage player, bool dealerHasBJ) private view returns (uint256 payout) { Player memory dealer = game.dealer; if (player.score == 21 && player.hand.length == 2 && !dealerHasBJ) { payout = SafeMath.div(SafeMath.mul(player.bet, 5), 2); // Blackjack pays 3:2 } else if (player.score > dealer.score || dealer.score >= 21) { payout = SafeMath.mul(SafeMath.add(player.bet, player.doubleDownBet), 2); } else if (player.score == dealer.score) { payout = SafeMath.add(player.bet, player.doubleDownBet); } else { payout = 0; } } /// Getters /// @notice Returns the dealer's opened hand /// @return hand The dealer's hand function getDealerState() public view returns (uint256[] memory hand, uint256 score) { Game storage game = games[msg.sender]; hand = game.dealer.hand; score = game.dealer.score; } /// @notice Returns all player's hands /// @return hand The player's primary hand /// @return splitHand The player's split hand, if any /// @return handScore Evaluated score for hand /// @return splitHandScore Evaluated score for split hand /// @return bet Original bet at start of hand function getPlayerState() public view returns ( uint256[] memory hand, uint256[] memory splitHand, uint256 handScore, uint256 splitHandScore, uint256 bet, uint256 splitBet, uint256 doubleDownBet, uint256 splitDoubleDownBet ) { Game storage game = games[msg.sender]; hand = game.player.hand; splitHand = game.splitPlayer.hand; handScore = game.player.score; splitHandScore = game.splitPlayer.score; bet = game.player.bet; splitBet = game.splitPlayer.bet; doubleDownBet = game.player.doubleDownBet; splitDoubleDownBet = game.splitPlayer.doubleDownBet; } /// @notice Returns selected elements from a game /// @dev Also add bet (and original) to return /// @return gameId ID for the current Blackjack game /// @return startTime Time the current Blackjack game began /// @return gameMaxBet Max bet allowed to be placed for new game /// @return round Number of round of Blackjack game played /// @return stage Stage of the Blackjack game function getGameState() public view returns ( uint256 gameId, uint64 startTime, uint256 gameMaxBet, uint64 round, Stage stage ) { Game storage game = games[msg.sender]; gameId = game.id; startTime = game.startTime; gameMaxBet = maxBet; round = game.round; stage = game.stage; } }
[Module 9, Lesson 3] Preventing integer overflow with SafeMath [Module 10, Lesson 1] Circuit breakers implemented here game The game to conclude, paying out players if necessary
function concludeGame(Game storage game) private stopInEmergency { uint payout = 0; bool dealerHasBJ = drawDealerCards(game); if (game.player.score <= 21) { payout = SafeMath.add(payout, calculatePayout(game, game.player, dealerHasBJ) ); } if (game.splitPlayer.score <= 21) { payout = SafeMath.add(payout, calculatePayout(game, game.splitPlayer, dealerHasBJ) ); } if (payout != 0) { msg.sender.transfer(payout); } emit Result(game.id, game.round, payout, game.player.score, game.dealer.score); }
14,034,403
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; contract PetAdopt { Adoption[16] public adopters; struct Adoption { address petOwner; uint256 date; } //Address from the shop which creates the Smart Contract address public owner; uint256 public last_withdraw; modifier onlyOwner() { // check if the owner is sending the tx require( msg.sender == owner); _; } modifier weekAfter() { require(block.timestamp > last_withdraw + 1 weeks); _; } constructor() public { owner = msg.sender; last_withdraw = block.timestamp; } event Adopted(address _adopter, uint256 _petId); function adopt(uint256 _petId) external { require(_petId >= 0 && _petId <= 15); require(adopters[_petId].petOwner == address(0x0)); adopters[_petId].petOwner = msg.sender; adopters[_petId].date = block.timestamp; emit Adopted(msg.sender, _petId); } function returnToShelter(uint256 _petId) public { require (adopters[_petId].petOwner == msg.sender); //Adopters can return the pet in a week time. require (block.timestamp < adopters[_petId].date + 7 days); adopters[_petId].petOwner = address(0x0); adopters[_petId].date = 0; } function getAdopters() public view returns (Adoption[16] memory) { return adopters; } //Allows the smart contract to accept money receive() external payable {} function withdraw() external onlyOwner weekAfter { last_withdraw = block.timestamp; msg.sender.transfer(address(this).balance); } function withdraw(uint256 amount) external onlyOwner weekAfter { last_withdraw = block.timestamp; msg.sender.transfer(amount); } }
Adopters can return the pet in a week time.
function returnToShelter(uint256 _petId) public { require (adopters[_petId].petOwner == msg.sender); require (block.timestamp < adopters[_petId].date + 7 days); adopters[_petId].petOwner = address(0x0); adopters[_petId].date = 0; }
14,122,320
./partial_match/1/0x26D471BdC7b88cf8524f4fF6fF7736B7f9da66AA/sources/TafectToken.sol
Approve token allowance by validating a message signed by the holder. _owner Address of the token holder _spender Address of the approved spender _value Amount of tokens to approve the spender _deadline Expiration time of the signed permit _v Signature version _r Signature r value _s Signature s value/
function permit(address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s) external { bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, nonces[_owner], _deadline)))); nonces[_owner] = nonces[_owner].add(1); address recoveredAddress = ECDSA.recover(digest, abi.encodePacked(_r, _s, _v)); require(_owner == recoveredAddress, "TAF: invalid permit"); require(_deadline == 0 || block.timestamp <= _deadline, "TAF: expired permit"); _approve(_owner, _spender, _value); }
15,953,986
// SPDX-License-Identifier: MIT // AND COPIED FROM https://github.com/compound-finance/compound-protocol/blob/c5fcc34222693ad5f547b14ed01ce719b5f4b000/contracts/Governance/Comp.sol // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/IVoteToken.sol"; import "hardhat/console.sol"; /** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by TRU and stkTRU to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */ abstract contract VoteToken is ERC20, IVoteToken { mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); function delegate(address delegatee) public override { return _delegate(msg.sender, delegatee); } /** * @dev Delegate votes using signature */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public override { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "LibToken::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "LibToken::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "LibToken::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @dev Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) public virtual override view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @dev Get voting power at a specific block for an account * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) public virtual override view returns (uint96) { require(blockNumber < block.number, "LibToken::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** * @dev Internal function to delegate voting power to an account * @param delegator Account to delegate votes from * @param delegatee Account to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; // OLD: uint96 delegatorBalance = balanceOf(delegator); uint96 delegatorBalance = safe96(_balanceOf(delegator), "LibToken: uint96 overflow"); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } function _transfer( address _from, address _to, uint256 _value ) internal virtual override { super._transfer(_from, _to, _value); _moveDelegates(delegates[_from], delegates[_to], safe96(_value, "LibToken: uint96 overflow")); } function _mint(address account, uint256 amount) internal virtual override { console.log("inside burner"); super._mint(account, amount); _moveDelegates(address(0), delegates[account], safe96(amount, "LibToken: uint96 overflow")); } function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _moveDelegates(delegates[account], address(0), safe96(amount, "LibToken: uint96 overflow")); } /** * @dev internal function to move delegates between accounts */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { console.log("moving delegation", srcRep, dstRep, amount); if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { console.log("write checkpoitn"); uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "LibTokens::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "LibTokens::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * @dev internal function to write a checkpoint for voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "LibToken::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * @dev internal function to get chain ID */ function getChainId() internal view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
internal function to write a checkpoint for voting power/
function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "LibToken::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); }
6,466,855
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPool} from '../../../interfaces/ILendingPool.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {WadRayMath} from '../../libraries/math/WadRayMath.sol'; import {Errors} from '../../libraries/helpers/Errors.sol'; import {VersionedInitializable} from '../../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from '../IncentivizedERC20.sol'; import {DataTypes} from '../../libraries/types/DataTypes.sol'; import {SignedSafeMath} from '../../../dependencies/openzeppelin/contracts/SignedSafeMath.sol'; import {UInt256Lib} from '../../../dependencies/uFragments/UInt256Lib.sol'; interface IAMPLDebtToken { function getAMPLBorrowData() external view returns (uint256, int256); } /** @title Aave-AMPL ERC20 AToken @dev Implementation of the interest bearing AMPL token for the Aave protocol @author AmpleforthOrg The AMPL AToken externally behaves similar to every other aTOKEN. It always maintains a 1:1 peg with the underlying AMPL. The following should always be true. 1) At any time, user can deposit x AMPLs to mint x aAMPLs. Total aAMPL supply increases by exactly x. 2) At any time, user can burn x aAMPLs for x AMPLs. Total aAMPL supply decreases by exactly x. 3) At any time, userA can transfer x aAMPLs to userB. userA's aAMPL balance reduces by X. userB's aAMPL balance increases by X. Total aAMPL supply exactly remains same. 4) When AMPL's supply rebases, only the 'unborrowed' aAMPL should rebase. * Say there are 1000 aAMPL, and 200 AMPL is lent out. AMPL expands by 10%. Thew new aAMPL supply should be 1080 aAMPL. * Say there are 1000 aAMPL, and 200 AMPL is lent out. AMPL contracts by 10%. Thew new aAMPL supply should be 920 aAMPL. 5) When AMPL's supply rebases, only the part of the balance of a user proportional to the available liquidity ('unborrowed') should rebase. * Say a user has deposited 1000 AMPL and receives 1000 aAMPL, and 20% of the total underlying AMPL is lent out. AMPL expands by 10%. The new aAMPL user balance should be 1080 aAMPL. * Say a user has deposited 1000 AMPL and receives 1000 aAMPL, and 20% of the total underlying AMPL is lent out. AMPL contracts by 10%. The new aAMPL supply should be 920 aAMPL. 6) The totalSupply of aAMPL should always be equal to (total AMPL held in the system) + (total principal borrowed denominated in AMPL) + (interest) Generic aToken: ATokens have a private balance and public balance. ``` # _balances[u] and _totalSupply from contract storage. Balance(u) = _balances[u] . I TotalSupply(supply) = _totalSupply . I ``` The internal (fixed-supply) balance and totalSupply are referred to as balanceScaled and scaledTotalSupply and correspond to the principal deposited. The external (elastic-supply) balance and totalSupply correspond to the principal + interest. AAMPL: AAMPL tokens have an additional scaling factor (multiplier) on top of the existing AToken structure. Thus they have 2 private balances and 1 public balance. * The internal (fixed-supply) balance and totalSupply are referred to as balanceInternal and totalSupplyInternal, used for book-keeping. * The internal (elastic-supply) balance and totalSupply are referred to as balanceScaled and scaledTotalSupply and correspond to the principal deposited. * The external (elastic-supply) balance and totalSupply correspond to the principal + interest. ``` # _balances[u] and _totalSupply from contract storage. Balance(u) = ( _balances[u] . λ ) . I where, * _balances[u] is called userBalanceInternal, raw value in contract's storage * (_balances[u] . λ) is called userBalanceScaled, aka principal deposited * (_balances[u] . λ) . I is the public userBalance, aka user's principal + interest * I is AAVE's interest rate factor * λ is the AAMPL scaling factor AND TotalSupply(u) = ( _totalSupply[u] . λ ) . I * _totalSupply[u] is called totalSupplyInternal, raw value in contract's storage * (_totalSupply[u] . λ) is called scaledTotalSupply, aka principal deposited * (_totalSupply[u] . λ) . I is the public totalSupply, aka principal + interest * I is AAVE's interest rate factor * λ is the AAMPL scaling factor ``` The AAMPL scaling factor λ is calculated as follows: ``` * Λ - Ampleforth co-efficient of expansion (retrieved from the AMPL contract) scaledTotalSupply = (totalGonsDeposited - totalGonsBorrowed) / Λ + totalPrincipalBorrowed λ = scaledTotalSupply / totalSupplyInternal ``` Additions: * The AAMPLToken stores references to the STABLE_DEBT_TOKEN, and the VARIABLE_DEBT_TOKEN contracts to calculate the total Principal borrowed (getAMPLBorrowData()), at any time. * On mint and burn a private variable `_totalGonsDeposited` keeps track of the scaled AMPL principal deposited. */ contract AAmplToken is VersionedInitializable, IncentivizedERC20, IAToken { using WadRayMath for uint256; using SafeERC20 for IERC20; using UInt256Lib for uint256; using SignedSafeMath for int256; bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); bytes32 public constant PERMIT_TYPEHASH = keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'); uint256 public constant ATOKEN_REVISION = 0x1; address public immutable UNDERLYING_ASSET_ADDRESS; address public immutable RESERVE_TREASURY_ADDRESS; ILendingPool public immutable POOL; /// @dev owner => next valid nonce to submit with permit() mapping(address => uint256) public _nonces; bytes32 public DOMAIN_SEPARATOR; // --------------------------------------------------------------------------- // aAMPL additions address public STABLE_DEBT_TOKEN_ADDRESS; address public VARIABLE_DEBT_TOKEN_ADDRESS; // This is a constant on the AMPL contract, which is used to calculate the scalar // which controls the AMPL expansion/contraction. // TOTAL_GONS/ampl.scaledTotalSupply, saving an external call to the AMPL contract // and setting it as a local contract constant. // NOTE: This should line up EXACTLY with the value on the AMPL contract uint256 private constant GONS_TOTAL_SUPPLY = uint256(type(int128).max); // Keeps track of the 'gons' deposited into the aave system int256 private _totalGonsDeposited; struct ExtData { uint256 totalAMPLSupply; uint256 totalPrincipalBorrowed; int256 totalGonsBorrowed; } // --------------------------------------------------------------------------- modifier onlyLendingPool { require(_msgSender() == address(POOL), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } constructor( ILendingPool pool, address underlyingAssetAddress, address reserveTreasuryAddress, string memory tokenName, string memory tokenSymbol, address incentivesController ) public IncentivizedERC20(tokenName, tokenSymbol, 18, incentivesController) { POOL = pool; UNDERLYING_ASSET_ADDRESS = underlyingAssetAddress; RESERVE_TREASURY_ADDRESS = reserveTreasuryAddress; } function getRevision() internal pure virtual override returns (uint256) { return ATOKEN_REVISION; } function setDebtTokens (address stableDebtTokenAddress, address variableDebtTokenAddress) public { require(STABLE_DEBT_TOKEN_ADDRESS == address(0) && VARIABLE_DEBT_TOKEN_ADDRESS == address(0)); STABLE_DEBT_TOKEN_ADDRESS = stableDebtTokenAddress; VARIABLE_DEBT_TOKEN_ADDRESS = variableDebtTokenAddress; } function initialize( uint8 underlyingAssetDecimals, string calldata tokenName, string calldata tokenSymbol ) external virtual initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(tokenName)), keccak256(EIP712_REVISION), chainId, address(this) ) ); _setName(tokenName); _setSymbol(tokenSymbol); _setDecimals(underlyingAssetDecimals); } /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); ExtData memory e = _fetchExtData(); _burnScaled(user, amountScaled, e); _totalGonsDeposited = _totalGonsDeposited.sub( _amplToGons(e.totalAMPLSupply, amountScaled).toInt256Safe() ); IERC20(UNDERLYING_ASSET_ADDRESS).safeTransfer(receiverOfUnderlying, amount); emit Transfer(user, address(0), amount); emit Burn(user, receiverOfUnderlying, amount, index); } /** * @dev Mints `amount` aTokens to `user` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { uint256 previousBalanceInternal = super.balanceOf(user); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); ExtData memory e = _fetchExtData(); _mintScaled(user, amountScaled, e); _totalGonsDeposited = _totalGonsDeposited.add( _amplToGons(e.totalAMPLSupply, amountScaled).toInt256Safe() ); emit Transfer(address(0), user, amount); emit Mint(user, amount, index); return previousBalanceInternal == 0; } /** * @dev Mints aTokens to the reserve treasury * - Only callable by the LendingPool * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { if (amount == 0) { return; } // Compared to the normal mint, we don't check for rounding errors. // The amount to mint can easily be very small since it is a fraction of the interest accrued. // In that case, the treasury will experience a (very small) loss, but it // wont cause potentially valid transactions to fail. uint256 amountScaled = amount.rayDiv(index); // require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); ExtData memory e = _fetchExtData(); _mintScaled(RESERVE_TREASURY_ADDRESS, amountScaled, e); _totalGonsDeposited = _totalGonsDeposited.add( _amplToGons(e.totalAMPLSupply, amountScaled).toInt256Safe() ); emit Transfer(address(0), RESERVE_TREASURY_ADDRESS, amount); emit Mint(RESERVE_TREASURY_ADDRESS, amount, index); } /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * - Only callable by the LendingPool * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external override onlyLendingPool { // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted // so no need to emit a specific event here _transfer(from, to, value, false); emit Transfer(from, to, value); } /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param target The recipient of the aTokens * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address target, uint256 amount) external override onlyLendingPool returns (uint256) { IERC20(UNDERLYING_ASSET_ADDRESS).safeTransfer(target, amount); return amount; } /** * @dev implements the permit function as for * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for 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(owner != address(0), 'INVALID_OWNER'); //solium-disable-next-line require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @dev Transfers the aTokens between two users. Validates the transfer * (ie checks for valid HF after the transfer) if required * @param from The source address * @param to The destination address * @param amount The amount getting transferred * @param validate `true` if the transfer needs to be validated **/ function _transfer( address from, address to, uint256 amount, bool validate ) internal { uint256 index = POOL.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS); uint256 amountScaled = amount.rayDiv(index); ExtData memory e = _fetchExtData(); uint256 totalSupplyInternal = super.totalSupply(); uint256 scaledTotalSupply = _scaledTotalSupply(e, _totalGonsDeposited); uint256 fromBalanceScaled = _scaledBalanceOf(super.balanceOf(from), totalSupplyInternal, scaledTotalSupply); uint256 toBalanceScaled = _scaledBalanceOf(super.balanceOf(to), totalSupplyInternal, scaledTotalSupply); uint256 fromBalanceBefore = fromBalanceScaled.rayMul(index); uint256 toBalanceBefore = toBalanceScaled.rayMul(index); _transferScaled(from, to, amountScaled, e); if (validate) { POOL.finalizeTransfer( UNDERLYING_ASSET_ADDRESS, from, to, amount, fromBalanceBefore, toBalanceBefore ); } emit BalanceTransfer(from, to, amount, index); } function _transfer( address from, address to, uint256 amount ) internal override { _transfer(from, to, amount, true); } // --------------------------------------------------------------------------- // View methods /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * aka, scaledTotalSupply = (totalGonsDeposited - totalGonsBorrowed) / Λ + totalPrincipalBorrowed * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return _scaledTotalSupply(_fetchExtData(), _totalGonsDeposited); } /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update. * aka, userBalanceScaled = userBalanceInternal/totalSupplyInternal * scaledTotalSupply * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view override returns (uint256) { return _scaledBalanceOf( super.balanceOf(user), super.totalSupply(), _scaledTotalSupply(_fetchExtData(), _totalGonsDeposited) ); } /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { uint256 scaledTotalSupply = _scaledTotalSupply(_fetchExtData(), _totalGonsDeposited); return ( _scaledBalanceOf(super.balanceOf(user), super.totalSupply(), scaledTotalSupply), scaledTotalSupply ); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) { uint256 currentSupplyScaled = _scaledTotalSupply(_fetchExtData(), _totalGonsDeposited); if (currentSupplyScaled == 0) { // currentSupplyInternal should also be zero in this case (super.totalSupply()) return 0; } return currentSupplyScaled.rayMul(POOL.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS)); } /** * @dev Calculates the balance of the user: principal balance + interest generated by the principal * @param user The user whose balance is calculated * @return The balance of the user **/ function balanceOf(address user) public view override(IncentivizedERC20, IERC20) returns (uint256) { uint256 userBalanceScaled = _scaledBalanceOf( super.balanceOf(user), super.totalSupply(), _scaledTotalSupply(_fetchExtData(), _totalGonsDeposited) ); return userBalanceScaled.rayMul(POOL.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS)); } // --------------------------------------------------------------------------- // AAMPL custom methods /** * @dev transferAmountInternal = (transferAmountScaled * totalSupplyInternal) / scaledTotalSupply **/ function _transferScaled(address from, address to, uint256 transferAmountScaled, ExtData memory e) private returns (uint256) { uint256 totalSupplyInternal = super.totalSupply(); uint256 scaledTotalSupply = _scaledTotalSupply(e, _totalGonsDeposited); uint256 transferAmountInternal = transferAmountScaled.mul(totalSupplyInternal).div(scaledTotalSupply); super._transfer(from, to, transferAmountInternal); } /** * @dev mintAmountInternal is mint such that the following holds true * * (userBalanceInternalBefore+mintAmountInternal)/(totalSupplyInternalBefore+mintAmountInternal) * = (userBalanceScaledBefore+mintAmountScaled)/(scaledTotalSupplyBefore+mintAmountScaled) * * scaledTotalSupplyAfter = scaledTotalSupplyBefore+mintAmountScaled * userBalanceScaledAfter = userBalanceScaledBefore+mintAmountScaled * otherBalanceScaledBefore = scaledTotalSupplyBefore-userBalanceScaledBefore * * mintAmountInternal = (totalSupplyInternalBefore*userBalanceScaledAfter - scaledTotalSupplyAfter*userBalanceInternalBefore)/otherBalanceScaledBefore **/ function _mintScaled(address user, uint256 mintAmountScaled, ExtData memory e) private { uint256 totalSupplyInternalBefore = super.totalSupply(); uint256 userBalanceInternalBefore = super.balanceOf(user); // First mint if(totalSupplyInternalBefore == 0) { uint256 mintAmountInternal = _amplToGons(e.totalAMPLSupply, mintAmountScaled); _mint(user, mintAmountInternal); return; } uint256 scaledTotalSupplyBefore = _scaledTotalSupply(e, _totalGonsDeposited); uint256 userBalanceScaledBefore = _scaledBalanceOf(userBalanceInternalBefore, totalSupplyInternalBefore, scaledTotalSupplyBefore); uint256 otherBalanceScaledBefore = scaledTotalSupplyBefore.sub(userBalanceScaledBefore); uint256 scaledTotalSupplyAfter = scaledTotalSupplyBefore.add(mintAmountScaled); uint256 userBalanceScaledAfter = userBalanceScaledBefore.add(mintAmountScaled); uint256 mintAmountInternal = 0; // Lone user if(otherBalanceScaledBefore == 0) { uint256 mintAmountInternal = mintAmountScaled.mul(totalSupplyInternalBefore).div(scaledTotalSupplyBefore); _mint(user, mintAmountInternal); return; } mintAmountInternal = totalSupplyInternalBefore .mul(userBalanceScaledAfter) .sub(scaledTotalSupplyAfter.mul(userBalanceInternalBefore)) .div(otherBalanceScaledBefore); _mint(user, mintAmountInternal); } /** * @dev burnAmountInternal is burnt such that the following holds true * * (userBalanceInternalBefore-burnAmountInternal)/(totalSupplyInternalBefore-burnAmountInternal) * = (userBalanceScaledBefore-burnAmountScaled)/(scaledTotalSupplyBefore-burnAmountScaled) * * scaledTotalSupplyAfter = scaledTotalSupplyBefore-burnAmountScaled * userBalanceScaledAfter = userBalanceScaledBefore-burnAmountScaled * otherBalanceScaledBefore = scaledTotalSupplyBefore-userBalanceScaledBefore * * burnAmountInternal = (scaledTotalSupplyAfter*userBalanceInternalBefore - totalSupplyInternalBefore*userBalanceScaledAfter)/otherBalanceScaledBefore **/ function _burnScaled(address user, uint256 burnAmountScaled, ExtData memory e) private { uint256 totalSupplyInternalBefore = super.totalSupply(); uint256 userBalanceInternalBefore = super.balanceOf(user); uint256 scaledTotalSupplyBefore = _scaledTotalSupply(e, _totalGonsDeposited); uint256 userBalanceScaledBefore = _scaledBalanceOf(userBalanceInternalBefore, totalSupplyInternalBefore, scaledTotalSupplyBefore); uint256 otherBalanceScaledBefore = scaledTotalSupplyBefore.sub(userBalanceScaledBefore); uint256 scaledTotalSupplyAfter = scaledTotalSupplyBefore.sub(burnAmountScaled); uint256 userBalanceScaledAfter = userBalanceScaledBefore.sub(burnAmountScaled); uint256 burnAmountInternal = 0; // Lone user if(otherBalanceScaledBefore == 0) { uint256 burnAmountInternal = burnAmountScaled.mul(totalSupplyInternalBefore).div(scaledTotalSupplyBefore); _burn(user, burnAmountInternal); return; } burnAmountInternal = scaledTotalSupplyAfter .mul(userBalanceInternalBefore) .sub(totalSupplyInternalBefore.mul(userBalanceScaledAfter)) .div(otherBalanceScaledBefore); _burn(user, burnAmountInternal); } /** * @dev balanceOfScaled = balanceInternal / totalSupplyInternal * scaledTotalSupply * = λ . balanceInternal **/ function _scaledBalanceOf(uint256 balanceInternal, uint256 totalSupplyInternal, uint256 scaledTotalSupply) private pure returns (uint256) { if (balanceInternal == 0 || scaledTotalSupply == 0) { return 0; } return balanceInternal.mul(scaledTotalSupply).div(totalSupplyInternal); } /** * @dev scaledTotalSupply = (totalGonsDeposited - totalGonsBorrowed) / Λ + totalPrincipalBorrowed * = λ . totalSupplyInternal **/ function _scaledTotalSupply(ExtData memory e, int256 totalGonsDeposited) private pure returns (uint256) { // require(totalGonsDeposited>=e.totalGonsBorrowed); return _gonsToAMPL(e.totalAMPLSupply, uint256(totalGonsDeposited.sub(e.totalGonsBorrowed))) .add(e.totalPrincipalBorrowed); } /** * @dev Helper method to convert gons to AMPL **/ function _gonsToAMPL(uint256 totalAMPLSupply, uint256 gonValue) private pure returns (uint256) { return gonValue.mul(totalAMPLSupply).div(GONS_TOTAL_SUPPLY); } /** * @dev Helper method to convert AMPL to gons **/ function _amplToGons(uint256 totalAMPLSupply, uint256 amplValue) private pure returns (uint256) { return amplValue.mul(GONS_TOTAL_SUPPLY).div(totalAMPLSupply); } /** * @dev Queries external contracts and fetches data used for aTokenMath * - AMPL scalar form Ampleforth ERC-20 (Λ) * - principal borrowed and Gons borrowed from the debt contracts **/ function _fetchExtData() internal view returns (ExtData memory) { ExtData memory _extContractData; _extContractData.totalAMPLSupply = IERC20(UNDERLYING_ASSET_ADDRESS).totalSupply(); uint256 stablePrincipal; int256 stablePrincipalScaled; (stablePrincipal, stablePrincipalScaled) = IAMPLDebtToken(STABLE_DEBT_TOKEN_ADDRESS).getAMPLBorrowData(); uint256 variablePrincipal; int256 variablePrincipalScaled; (variablePrincipal, variablePrincipalScaled) = IAMPLDebtToken(VARIABLE_DEBT_TOKEN_ADDRESS).getAMPLBorrowData(); _extContractData.totalPrincipalBorrowed = stablePrincipal.add(variablePrincipal); _extContractData.totalGonsBorrowed = stablePrincipalScaled.add(variablePrincipalScaled); return _extContractData; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @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.12; import {IERC20} from './IERC20.sol'; import {SafeMath} from './SafeMath.sol'; import {Address} from './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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; interface ILendingPool { /** * @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 * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @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 * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @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 (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @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 ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); 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 getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; 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; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; 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} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; interface IAToken is IERC20, IScaledBalanceToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the aTokens * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) * - AT = AToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = LendingPoolAddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolCollateralManager * - P = Pausable */ library Errors { //common errors string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin' string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator' string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin' string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" string public constant LPCM_NO_ERRORS = '46'; // 'No errors' string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant LP_FAILED_COLLATERAL_SWAP = '60'; string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string public constant UL_INVALID_INDEX = '77'; string public constant LP_NOT_CONTRACT = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title VersionedInitializable * * @dev Helper contract to implement initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require( initializing || isConstructor() || revision > lastInitializedRevision, 'Contract instance has already been initialized' ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /** * @dev returns the revision number of the contract * Needs to be defined in the inherited class as a constant. **/ function getRevision() internal pure virtual returns (uint256); /** * @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. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address()) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title ERC20 * @notice Basic ERC20 implementation * @author Aave, inspired by the Openzeppelin ERC20 implementation **/ contract IncentivizedERC20 is Context, IERC20, IERC20Detailed { using SafeMath for uint256; IAaveIncentivesController internal immutable _incentivesController; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 internal _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor( string memory name, string memory symbol, uint8 decimals, address incentivesController ) public { _name = name; _symbol = symbol; _decimals = decimals; _incentivesController = IAaveIncentivesController(incentivesController); } /** * @return The name of the token **/ function name() public view override returns (string memory) { return _name; } /** * @return The symbol of the token **/ function symbol() public view override returns (string memory) { return _symbol; } /** * @return The decimals of the token **/ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total supply of the token **/ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @return The balance of the token **/ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev Executes a transfer of tokens from _msgSender() to recipient * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); emit Transfer(_msgSender(), recipient, amount); return true; } /** * @dev Returns the allowance of spender on the tokens owned by owner * @param owner The owner of the tokens * @param spender The user allowed to spend the owner's tokens * @return The amount of owner's tokens spender is allowed to spend **/ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Allows `spender` to spend the tokens owned by _msgSender() * @param spender The user allowed to spend _msgSender() tokens * @return `true` **/ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so * @param sender The owner of the tokens * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ 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') ); emit Transfer(sender, recipient, amount); return true; } /** * @dev Increases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param addedValue The amount being added to the allowance * @return `true` **/ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Decreases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param subtractedValue The amount being subtracted to the allowance * @return `true` **/ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } function _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 oldSenderBalance = _balances[sender]; _balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance'); uint256 oldRecipientBalance = _balances[recipient]; _balances[recipient] = _balances[recipient].add(amount); if (address(_incentivesController) != address(0)) { uint256 currentTotalSupply = _totalSupply; _incentivesController.handleAction(sender, currentTotalSupply, oldSenderBalance); if (sender != recipient) { _incentivesController.handleAction(recipient, currentTotalSupply, oldRecipientBalance); } } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.add(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.sub(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance'); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setName(string memory newName) internal { _name = newName; } function _setSymbol(string memory newSymbol) internal { _symbol = newSymbol; } function _setDecimals(uint8 newDecimals) internal { _decimals = newDecimals; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* * @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: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAaveIncentivesController { function handleAction( address user, uint256 userBalance, uint256 totalSupply ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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: agpl-3.0 pragma solidity 0.6.12; /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } }
Returns the scaled total supply of the variable debt token. Represents sum(debt/index) aka, scaledTotalSupply = (totalGonsDeposited - totalGonsBorrowed) / Λ + totalPrincipalBorrowed return the scaled total supply/
function scaledTotalSupply() public view virtual override returns (uint256) { return _scaledTotalSupply(_fetchExtData(), _totalGonsDeposited); }
13,851,315
/** *Submitted for verification at Etherscan.io on 2022-05-03 */ //SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/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/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' 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"); } } } // 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/utils/ERC721Holder.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/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/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/cryptography/ECDSA.sol // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^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 { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) public pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File: @openzeppelin/contracts/utils/cryptography/draft-EIP712.sol // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/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 {} } /** * @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); /** * @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); } /** * @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/ERC721URIStorage.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: 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)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { // super._burn(tokenId); // if (bytes(_tokenURIs[tokenId]).length != 0) { // delete _tokenURIs[tokenId]; // } // } } // File: @openzeppelin/contracts/access/IAccessControl.sol // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File: @openzeppelin/contracts/access/AccessControl.sol // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @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()); } } } // File: lazy.sol pragma solidity ^0.8.0; pragma abicoder v2; // required to accept structs as function parameters pragma solidity ^0.8.0; interface IMarketplace { struct Order { // Order ID // bytes32 id; // Owner of the NFT address seller; // NFT registry address address nftAddress; // Price (in wei) for the published item uint256 price; // Time when this sale ends uint256 expiresAt; // ERC20 currency address address currency; // royalty uint256 royalty; // NFT Metadata URI string uri; //signature bytes signature; // is New collection bool isNewColl; // unlockable content string lockedContent; } struct NewCollection { // Collection name string name; // Collection symbol string symbol; // Collection baseURI string baseURI; } struct Bid { // Bid Id bytes32 id; // Bid Count // uint256 bidCount; // Bidder address address bidder; // Time when bid was created uint256 price; // Time when this bid ends uint256 expiresAt; } // ORDER EVENTS event OrderCreated( bytes id, address indexed seller, address indexed nftAddress, uint256 priceInWei, uint256 expiresAt, address currency ); event OrderUpdated( bytes id, uint256 priceInWei, uint256 expiresAt ); event OrderSuccessful( bytes id, address indexed buyer, uint256 priceInWei ); event OrderCancelled(bytes id); // BID EVENTS event BidCreated( bytes32 id, // uint256 number, address indexed nftAddress, bytes indexed order, address indexed bidder, uint256 priceInWei, uint256 expiresAt ); event BidAccepted(bytes32 id); event BidCancelled(bytes32 id); } pragma solidity ^0.8.0; contract FeeManager is Ownable { event ChangedFeePerMillion(uint256 cutPerMillion); // Market fee on sales uint256 public cutPerMillion; uint256 public constant maxCutPerMillion = 100000; // 10% cut /** * @dev Sets the share cut for the owner of the contract that's * charged to the seller on a successful sale * @param _cutPerMillion - Share amount, from 0 to 99,999 */ function setOwnerCutPerMillion(uint256 _cutPerMillion) external onlyOwner { require( _cutPerMillion < maxCutPerMillion, "The owner cut should be between 0 and maxCutPerMillion" ); cutPerMillion = _cutPerMillion; emit ChangedFeePerMillion(cutPerMillion); } } contract OpenMarketplace is Ownable, Pausable, FeeManager, IMarketplace, ERC721Holder, EIP712, AccessControl, ERC721Enumerable, ERC721URIStorage { using Address for address; using SafeMath for uint256; using SafeERC20 for IERC20; using ECDSA for bytes32; // IERC20 public acceptedToken; address public nftToken; string private constant SIGNING_DOMAIN = "LazyNFT-Voucher"; string private constant SIGNATURE_VERSION = "1"; // From ERC721 registry assetId to Order (to avoid asset collision) mapping(bytes => Order) public orderByAssetId; // From ERC721 registry assetId to NewCollection (to avoid asset collision) mapping(bytes => NewCollection) public newCollectionByAssetId; // From ERC721 registry assetId to Bid (to avoid asset collision)lockedContent mapping(bytes => Bid) public bidByOrderId; // From IERC20 to status for toggling accepted currencies mapping (address => bool) public acceptedCurrencies; // Mocking a constant for ether as currency address public constant MARKETPLACE_ETHER = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; mapping(uint256 => address) public tokenCreator; //royality mapping to particular seller mapping(address => uint256) public sellerRoyality; mapping(uint256 => string) public userLockedContent; // 721 Interfaces bytes4 public constant _INTERFACE_ID_ERC721 = 0x80ac58cd; // uint256 public royaltyPercent; /*** * @dev Initialize this contract. Acts as a constructor * @param _acceptedToken - currency for payments */ constructor() public Ownable() EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) ERC721("Nft","NFT") { // require(_acceptedToken.isContract(),"The accepted token address must be a deployed contract"); // acceptedToken = IERC20(_acceptedToken); acceptedCurrencies[MARKETPLACE_ETHER] = true; nftToken = address(this); } /** * @dev Set accepted currencies as payments. Can only be called by owner * @param _token - ERC20 contract address * @param _status - status for the token */ function setCurrency(address _token, bool _status) external onlyOwner { require(_token.isContract(),"The accepted token address must be a deployed contract"); acceptedCurrencies[_token] = _status; } /** * @dev Creates a new order * @param _priceInWei - Price in Wei for the supported coin * @param _expiresAt - Duration of the order (in hours) * @param _uri - Duration of the order (in hours) */ function createOrder(uint256 _priceInWei, uint256 _expiresAt, address _currency, string memory _uri, bytes memory _signature, uint256 _royalty, bool _isNewColl, string memory _name, string memory _symbol, string memory _baseURI, string memory _lockedContent) public whenNotPaused { _createOrder(_priceInWei, _expiresAt, _currency, _uri, _signature, _royalty, _isNewColl, _name, _symbol, _baseURI, _lockedContent); } /** * @dev Cancel an already published order * can only be canceled by seller or the contract owner */ function cancelOrder(Order memory _order) public whenNotPaused { // Order memory order = orderByAssetId[nftToken][_assetId]; address signer = _verify(_order); require(_order.seller == msg.sender || msg.sender == owner(), "Marketplace: unauthorized sender"); // Remove pending bid if any Bid memory bid = bidByOrderId[_order.signature]; if (bid.id != 0) { _cancelBid(_order, bid.id, bid.bidder, bid.price); } // Cancel order. _cancelOrder(_order); } /*** * @dev Update an already published order * can only be updated by seller * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT */ function updateOrder(Order memory _order, uint256 _priceInWei, uint256 _expiresAt) public whenNotPaused { Order storage order = orderByAssetId[_order.signature]; // Check valid order to update require(order.seller == msg.sender, "Marketplace: sender not allowed"); require(order.expiresAt >= block.timestamp, "Marketplace: order expired"); // check order updated params require(_priceInWei > 0, "Marketplace: Price should be bigger than 0"); require(_expiresAt > block.timestamp.add(1 minutes), "Marketplace: Expire time should be more than 1 minute in the future"); order.price = _priceInWei; order.expiresAt = _expiresAt; emit OrderUpdated(_order.signature, _priceInWei, _expiresAt); } /** * @dev Executes the sale for a published NFT */ function safeExecuteOrder(Order calldata _order) public payable whenNotPaused { // Get the current valid order for the asset or fail Order memory order = orderByAssetId[_order.signature]; require(order.price == _order.price, "Amount not correct"); require(order.seller != msg.sender, "Marketplace: unauthorized sender"); require(order.expiresAt >= block.timestamp, "Marketplace: order expired"); order.currency == MARKETPLACE_ETHER ? require(order.price == msg.value, "Marketplace: invalid price") : require(order.price == order.price, "Marketplace: invalid price"); uint256 tokenId = totalSupply(); if(!order.isNewColl) { _mint(msg.sender, tokenId); _setTokenURI(tokenId, order.uri); sellerRoyality[order.seller]= order.royalty; tokenCreator[tokenId] = order.seller; userLockedContent[tokenId] = order.lockedContent; } // market fee to cut uint256 saleShareAmount = 0; // Send market fees to owner if (FeeManager.cutPerMillion > 0) { // Calculate sale share saleShareAmount = order.price.mul(FeeManager.cutPerMillion).div(1e6); // Transfer share amount for marketplace Owner order.currency == MARKETPLACE_ETHER ? payable(owner()).transfer(saleShareAmount) : IERC20(order.currency).safeTransferFrom(msg.sender,owner(),saleShareAmount); } // Transfer token amount minus market fee to seller order.currency == MARKETPLACE_ETHER ? payable(order.seller).transfer(order.price.sub(saleShareAmount)) : IERC20(order.currency).safeTransferFrom(msg.sender, order.seller, order.price.sub(saleShareAmount)); // Remove pending bid if any Bid memory bid = bidByOrderId[order.signature]; if (bid.id != 0) { _cancelBid(_order, bid.id, bid.bidder, bid.price); } _executeOrder(order); } /** * @dev Places a bid for a published NFT * @param _priceInWei - Bid price in acceptedToken currency * @param _expiresAt - Bid expiration time */ function safePlaceBid(Order memory _order, uint256 _priceInWei, uint256 _expiresAt) public payable whenNotPaused { Order memory order = orderByAssetId[_order.signature]; order.currency == MARKETPLACE_ETHER ? _createBid(_order, msg.value, _expiresAt) : _createBid(_order, _priceInWei, _expiresAt); } /** * @dev Cancel an already published bid * can only be canceled by seller or the contract owner */ function cancelBid(Order memory _order) public whenNotPaused { Bid memory bid = bidByOrderId[_order.signature]; require(bid.bidder == msg.sender || msg.sender == owner(),"Marketplace: Unauthorized sender"); _cancelBid(_order, bid.id, bid.bidder, bid.price); } /** * @dev Executes the sale for a published NFT by accepting a current bid */ function acceptBid(Order memory _order) public whenNotPaused { // check order validity // Order memory order = getValidOrder(order); Order memory order = orderByAssetId[_order.signature]; // require(order.id != 0, "Marketplace: asset not published"); require(order.expiresAt >= block.timestamp, "Marketplace: order expired"); address signer = _verify(_order); // item seller is the only allowed to accept a bid require(order.seller == msg.sender, "Signature invalid or unauthorized"); Bid memory bid = bidByOrderId[order.signature]; // require(bid.price == _priceInWei, "Marketplace: invalid bid price"); require(bid.expiresAt >= block.timestamp, "Marketplace: the bid expired"); uint256 tokenId = totalSupply(); if(!order.isNewColl) { _mint(bid.bidder, tokenId); _setTokenURI(tokenId, order.uri); tokenCreator[tokenId] = order.seller; sellerRoyality[order.seller]= order.royalty; userLockedContent[tokenId] = order.lockedContent; } // remove bid delete bidByOrderId[order.signature]; emit BidAccepted(bid.id); uint256 saleShareAmount = 0; // Send market fees to owner if (FeeManager.cutPerMillion > 0) { // Calculate sale share saleShareAmount = bid.price.mul(FeeManager.cutPerMillion).div(1e6); // Transfer share amount for marketplace Owner order.currency == MARKETPLACE_ETHER ? payable(owner()).transfer(saleShareAmount) : IERC20(order.currency).safeTransfer(owner(), saleShareAmount); } // Transfer token amount minus market fee to seller order.currency == MARKETPLACE_ETHER ? payable(order.seller).transfer(bid.price.sub(saleShareAmount)) : IERC20(order.currency).safeTransfer(order.seller, bid.price.sub(saleShareAmount)); _executeOrder(order); } /** * @dev Executes the sale for a published NFT */ function _executeOrder(Order memory _order) internal { // remove order delete orderByAssetId[_order.signature]; // Notify .. emit OrderSuccessful(_order.signature, msg.sender, _order.price); } /** * @dev Creates a new order * @param _priceInWei - Price in Wei for the supported coin * @param _expiresAt - Expiration time for the order * @param _uri - nft Metadata URI */ function _createOrder(uint256 _priceInWei, uint256 _expiresAt, address _currency, string memory _uri, bytes memory _signature, uint256 _royalty, bool _isNewColl, string memory _name, string memory _symbol, string memory _baseURI, string memory _lockedContent) internal { // Check _acceptedCurrency require( acceptedCurrencies[_currency], "Marketplace: Unacceptable marketplace currency" ); require(_priceInWei > 0, "Marketplace: Price should be bigger than 0"); require( _expiresAt > block.timestamp.add(1 minutes), "Marketplace: Publication should be more than 1 minute in the future" ); // create the orderId // bytes32 orderId = keccak256(abi.encodePacked(block.timestamp, msg.sender, _priceInWei, _uri)); // save order orderByAssetId[_signature] = Order({ // id: orderId, seller: msg.sender, nftAddress: address(this), price: _priceInWei, expiresAt: _expiresAt, currency: _currency, uri: _uri, signature: _signature, royalty: _royalty, isNewColl: _isNewColl, lockedContent: _lockedContent }); if(_isNewColl) { newCollectionByAssetId[_signature] = NewCollection({ name: _name, symbol: _symbol, baseURI: _baseURI }); } emit OrderCreated(_signature, msg.sender, nftToken, _priceInWei, _expiresAt, _currency); } /** * @dev Creates a new bid on a existing order * @param _priceInWei - Price in Wei for the supported coin * @param _expiresAt - expires time */ function _createBid(Order memory _order, uint256 _priceInWei, uint256 _expiresAt) internal { // Checks order validity Order memory order = orderByAssetId[_order.signature]; // require(order.id != 0, "Marketplace: asset not published"); require(order.expiresAt >= block.timestamp, "Marketplace: order expired"); // check on expire time if (_expiresAt > _order.expiresAt) { _expiresAt = _order.expiresAt; } // Check price if theres previous a bid Bid memory bid = bidByOrderId[_order.signature]; // if theres no previous bid, just check price > 0 if (bid.id != 0) { if (bid.expiresAt >= block.timestamp) { require( _priceInWei > bid.price, "Marketplace: bid price should be higher than last bid" ); } else { require(_priceInWei > 0, "Marketplace: bid should be > 0"); } _cancelBid(_order, bid.id, bid.bidder, bid.price); } else { require(_priceInWei > 0, "Marketplace: bid should be > 0"); } if(order.currency != 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE){ IERC20(address(order.currency)).transferFrom(msg.sender, address(this), _priceInWei); } // Create bid bytes32 bidId = keccak256(abi.encodePacked(block.timestamp, msg.sender, _order.signature, _priceInWei, _expiresAt)); // Save Bid for this order bidByOrderId[_order.signature] = Bid({ id: bidId, // bidCount: currectBidCount.add(1), bidder: msg.sender, price: _priceInWei, expiresAt: _expiresAt }); // currectBidCount = currectBidCount.add(1); emit BidCreated(bidId, nftToken, order.signature, msg.sender, _priceInWei, _expiresAt); } /** * @dev Cancel an already published order * can only be canceled by seller or the contract owner */ function _cancelOrder(Order memory _order) internal { delete orderByAssetId[_order.signature]; emit OrderCancelled(_order.signature); } /** * @dev Cancel bid from an already published order * can only be canceled by seller or the contract owner * @param _bidId - Bid identifier * @param _bidder - Address * @param _escrowAmount - in acceptenToken currency */ function _cancelBid(Order memory _order, bytes32 _bidId, address _bidder, uint256 _escrowAmount) internal { delete bidByOrderId[_order.signature]; Order storage order = orderByAssetId[_order.signature]; order.currency == MARKETPLACE_ETHER ? payable(_bidder).transfer(_escrowAmount) : IERC20(order.currency).safeTransfer(_bidder, _escrowAmount); emit BidCancelled(_bidId); } /// @notice Returns a hash of the given Order, prepared using EIP712 typed data hashing rules. /// @param _order An Order to hash. function _hash(Order memory _order) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("Order(address seller,address nftAddress,uint256 price,uint256 expiresAt,uint256 royalty,string uri)"), _order.seller, _order.nftAddress, _order.price, _order.expiresAt, _order.royalty, keccak256(bytes(_order.uri)) ))); } /// @notice Returns the chain id of the current blockchain. /// @dev This is used to workaround an issue with ganache returning different values from the on-chain chainid() function and /// the eth_chainId RPC method. See https://github.com/protocol/nft-website/issues/121 for context. function getChainID() external view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } // @notice Verifies the signature for a given NFTVoucher, returning the address of the signer. // @dev Will revert if the signature is invalid. Does not verify that the signer is authorized to mint NFTs. // @param voucher An NFTVoucher describing an unminted NFT. function _verify(Order memory _order) public view returns (address) { bytes32 digest = _hash(_order); address user = ECDSA.recover(digest, _order.signature); return user; } function supportsInterface(bytes4 interfaceId) public view override(AccessControl, ERC721, ERC721Enumerable) returns (bool) { return ERC721.supportsInterface(interfaceId) || AccessControl.supportsInterface(interfaceId) || ERC721Enumerable.supportsInterface(interfaceId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { super.tokenURI(tokenId); } function getTokenMinter(uint256 _tokenId) external view returns (address) { return tokenCreator[_tokenId]; } // returns the string "locked", only available for the owner function unlockContent(uint256 _tokenId) public view returns (string memory) { require(this.ownerOf(_tokenId) == msg.sender, "Not the owner"); return userLockedContent[_tokenId]; } }
Cancel an already published order can only be canceled by seller or the contract owner/ Order memory order = orderByAssetId[nftToken][_assetId]; Remove pending bid if any
function cancelOrder(Order memory _order) public whenNotPaused { address signer = _verify(_order); require(_order.seller == msg.sender || msg.sender == owner(), "Marketplace: unauthorized sender"); Bid memory bid = bidByOrderId[_order.signature]; if (bid.id != 0) { _cancelBid(_order, bid.id, bid.bidder, bid.price); } }
2,316,773
./partial_match/1/0xC94BEd0F0bbCd0fb12b98c829B63a892F4d57976/sources/CryptoFish.sol
Initializes the contract setting the deployer as the initial owner./
function _afterTokenTransfer( address from, address to, uint256 firstTokenId, uint256 batchSize } constructor() { _transferOwnership(_msgSender()); }
9,273,595
// SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[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]; } }
SPDX-License-Identifier: GPL-3.0/ IComptroller Interface Enzyme Council <[email protected]>
interface IComptroller { function validatePolicies( address, PolicyHook, bytes calldata ) 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; enum VaultAction { None, BurnShares, MintShares, TransferShares, ApproveAssetSpender, WithdrawAssetTo, AddTrackedAsset, RemoveTrackedAsset } }
1,696,767
./full_match/1/0x467a2B91f231D930F5eeB6B982C7666E81DA8626/sources/contracts/nft/libs/ERC721.sol
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 { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); }
3,857,765
// File: contracts/external/openzeppelin-solidity/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } library SafeMath64 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a, "SafeMath: subtraction overflow"); uint64 c = a - b; return c; } /** * @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(uint64 a, uint64 b, string memory errorMessage) internal pure returns (uint64) { require(b <= a, errorMessage); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // 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; } uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts/external/proxy/Proxy.sol pragma solidity 0.5.7; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ contract Proxy { /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function () external payable { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view returns (address); } // File: contracts/external/proxy/UpgradeabilityProxy.sol pragma solidity 0.5.7; /** * @title UpgradeabilityProxy * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded */ contract UpgradeabilityProxy is Proxy { /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); // Storage position of the address of the current implementation bytes32 private constant IMPLEMENTATION_POSITION = keccak256("org.govblocks.proxy.implementation"); /** * @dev Constructor function */ constructor() public {} /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address impl) { bytes32 position = IMPLEMENTATION_POSITION; assembly { impl := sload(position) } } /** * @dev Sets the address of the current implementation * @param _newImplementation address representing the new implementation to be set */ function _setImplementation(address _newImplementation) internal { bytes32 position = IMPLEMENTATION_POSITION; assembly { sstore(position, _newImplementation) } } /** * @dev Upgrades the implementation address * @param _newImplementation representing the address of the new implementation to be set */ function _upgradeTo(address _newImplementation) internal { address currentImplementation = implementation(); require(currentImplementation != _newImplementation); _setImplementation(_newImplementation); emit Upgraded(_newImplementation); } } // File: contracts/external/proxy/OwnedUpgradeabilityProxy.sol pragma solidity 0.5.7; /** * @title OwnedUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); // Storage position of the owner of the contract bytes32 private constant PROXY_OWNER_POSITION = keccak256("org.govblocks.proxy.owner"); /** * @dev the constructor sets the original owner of the contract to the sender account. */ constructor(address _implementation) public { _setUpgradeabilityOwner(msg.sender); _upgradeTo(_implementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the owner * @return the address of the owner */ function proxyOwner() public view returns (address owner) { bytes32 position = PROXY_OWNER_POSITION; assembly { owner := sload(position) } } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferProxyOwnership(address _newOwner) public onlyProxyOwner { require(_newOwner != address(0)); _setUpgradeabilityOwner(_newOwner); emit ProxyOwnershipTransferred(proxyOwner(), _newOwner); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy. * @param _implementation representing the address of the new implementation to be set. */ function upgradeTo(address _implementation) public onlyProxyOwner { _upgradeTo(_implementation); } /** * @dev Sets the address of the owner */ function _setUpgradeabilityOwner(address _newProxyOwner) internal { bytes32 position = PROXY_OWNER_POSITION; assembly { sstore(position, _newProxyOwner) } } } // File: contracts/interfaces/IMarketUtility.sol pragma solidity 0.5.7; contract IMarketUtility { function initialize(address payable[] calldata _addressParams, address _initiater) external; /** * @dev to Set authorized address to update parameters */ function setAuthorizedAddres() public; /** * @dev to update uint parameters in Market Config */ function updateUintParameters(bytes8 code, uint256 value) external; /** * @dev to Update address parameters in Market Config */ function updateAddressParameters(bytes8 code, address payable value) external; /** * @dev Get Parameters required to initiate market * @return Addresses of tokens to be distributed as incentives * @return Cool down time for market * @return Rate * @return Commission percent for predictions with ETH * @return Commission percent for predictions with PLOT **/ function getMarketInitialParams() public view returns(address[] memory, uint , uint, uint, uint); function getAssetPriceUSD(address _currencyAddress) external view returns(uint latestAnswer); function getPriceFeedDecimals(address _priceFeed) public view returns(uint8); function getValueAndMultiplierParameters(address _asset, uint256 _amount) public view returns (uint256, uint256); function update() external; function calculatePredictionValue(uint[] memory params, address asset, address user, address marketFeedAddress, bool _checkMultiplier) public view returns(uint _predictionValue, bool _multiplierApplied); /** * @dev Get basic market details * @return Minimum amount required to predict in market * @return Percentage of users leveraged amount to deduct when placed in wrong prediction * @return Decimal points for prediction positions **/ function getBasicMarketDetails() public view returns ( uint256, uint256, uint256, uint256 ); function getDisputeResolutionParams() public view returns (uint256); function calculateOptionPrice(uint[] memory params, address marketFeedAddress) public view returns(uint _optionPrice); /** * @dev Get price of provided feed address * @param _currencyFeedAddress Feed Address of currency on which market options are based on * @return Current price of the market currency **/ function getSettlemetPrice( address _currencyFeedAddress, uint256 _settleTime ) public view returns (uint256 latestAnswer, uint256 roundId); /** * @dev Get value of provided currency address in ETH * @param _currencyAddress Address of currency * @param _amount Amount of provided currency * @return Value of provided amount in ETH **/ function getAssetValueETH(address _currencyAddress, uint256 _amount) public view returns (uint256 tokenEthValue); } // File: contracts/interfaces/IToken.sol pragma solidity 0.5.7; contract IToken { function decimals() external view returns(uint8); /** * @dev Total number of tokens in existence */ function totalSupply() external view returns (uint256); /** * @dev Gets the balance of the specified address. * @param account The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address account) external view returns (uint256); /** * @dev Transfer token for a specified address * @param recipient The address to transfer to. * @param amount The amount to be transferred. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) external returns (bool); /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) external; /** * @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. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Transfer tokens from one address to another * @param sender address The address which you want to send tokens from * @param recipient address The address which you want to transfer to * @param amount uint256 the amount of tokens to be transferred */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // File: contracts/interfaces/ITokenController.sol pragma solidity 0.5.7; contract ITokenController { address public token; address public bLOTToken; /** * @dev Swap BLOT token. * account. * @param amount The amount that will be swapped. */ function swapBLOT(address _of, address _to, uint256 amount) public; function totalBalanceOf(address _of) public view returns (uint256 amount); function transferFrom(address _token, address _of, address _to, uint256 amount) public; /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burnCommissionTokens(uint256 amount) external returns(bool); function initiateVesting(address _vesting) external; function lockForGovernanceVote(address _of, uint _days) public; function totalSupply() public view returns (uint256); function mint(address _member, uint _amount) public; } // File: contracts/interfaces/IMarketRegistry.sol pragma solidity 0.5.7; contract IMarketRegistry { enum MarketType { HourlyMarket, DailyMarket, WeeklyMarket } address public owner; address public tokenController; address public marketUtility; bool public marketCreationPaused; mapping(address => bool) public isMarket; function() external payable{} function marketDisputeStatus(address _marketAddress) public view returns(uint _status); function burnDisputedProposalTokens(uint _proposaId) external; function isWhitelistedSponsor(address _address) public view returns(bool); function transferAssets(address _asset, address _to, uint _amount) external; /** * @dev Initialize the PlotX. * @param _marketConfig The address of market config. * @param _plotToken The address of PLOT token. */ function initiate(address _defaultAddress, address _marketConfig, address _plotToken, address payable[] memory _configParams) public; /** * @dev Create proposal if user wants to raise the dispute. * @param proposalTitle The title of proposal created by user. * @param description The description of dispute. * @param solutionHash The ipfs solution hash. * @param actionHash The action hash for solution. * @param stakeForDispute The token staked to raise the diospute. * @param user The address who raises the dispute. */ function createGovernanceProposal(string memory proposalTitle, string memory description, string memory solutionHash, bytes memory actionHash, uint256 stakeForDispute, address user, uint256 ethSentToPool, uint256 tokenSentToPool, uint256 proposedValue) public { } /** * @dev Emits the PlacePrediction event and sets user data. * @param _user The address who placed prediction. * @param _value The amount of ether user staked. * @param _predictionPoints The positions user will get. * @param _predictionAsset The prediction assets user will get. * @param _prediction The option range on which user placed prediction. * @param _leverage The leverage selected by user at the time of place prediction. */ function setUserGlobalPredictionData(address _user,uint _value, uint _predictionPoints, address _predictionAsset, uint _prediction,uint _leverage) public{ } /** * @dev Emits the claimed event. * @param _user The address who claim their reward. * @param _reward The reward which is claimed by user. * @param incentives The incentives of user. * @param incentiveToken The incentive tokens of user. */ function callClaimedEvent(address _user , uint[] memory _reward, address[] memory predictionAssets, uint incentives, address incentiveToken) public { } /** * @dev Emits the MarketResult event. * @param _totalReward The amount of reward to be distribute. * @param _winningOption The winning option of the market. * @param _closeValue The closing value of the market currency. */ function callMarketResultEvent(uint[] memory _totalReward, uint _winningOption, uint _closeValue, uint roundId) public { } } // File: contracts/Market.sol /* Copyright (C) 2020 PlotX.io 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/ */ pragma solidity 0.5.7; contract Market { using SafeMath for *; enum PredictionStatus { Live, InSettlement, Cooling, InDispute, Settled } struct option { uint predictionPoints; mapping(address => uint256) assetStaked; mapping(address => uint256) assetLeveraged; } struct MarketSettleData { uint64 WinningOption; uint64 settleTime; } address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address constant marketFeedAddress = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c; address constant plotToken = 0x72F020f8f3E8fd9382705723Cd26380f8D0c66Bb; IMarketRegistry constant marketRegistry = IMarketRegistry(0xE210330d6768030e816d223836335079C7A0c851); ITokenController constant tokenController = ITokenController(0x12d7053Efc680Ba6671F8Cb96d1421D906ce3dE2); IMarketUtility constant marketUtility = IMarketUtility(0x2330058D49fA61D5C5405fA8B17fcD823c59F7Bb); uint8 constant roundOfToNearest = 25; uint constant totalOptions = 3; uint constant MAX_LEVERAGE = 5; uint constant ethCommissionPerc = 10; //with 2 decimals uint constant plotCommissionPerc = 5; //with 2 decimals bytes32 public constant marketCurrency = "B/USD"; bool internal lockedForDispute; address internal incentiveToken; uint internal ethAmountToPool; uint internal ethCommissionAmount; uint internal plotCommissionAmount; uint internal tokenAmountToPool; uint internal incentiveToDistribute; uint[] internal rewardToDistribute; PredictionStatus internal predictionStatus; struct UserData { bool claimedReward; bool predictedWithBlot; bool multiplierApplied; mapping(uint => uint) predictionPoints; mapping(address => mapping(uint => uint)) assetStaked; mapping(address => mapping(uint => uint)) LeverageAsset; } struct MarketData { uint64 startTime; uint64 predictionTime; uint64 neutralMinValue; uint64 neutralMaxValue; } MarketData public marketData; MarketSettleData public marketSettleData; mapping(address => UserData) internal userData; mapping(uint=>option) public optionsAvailable; /** * @dev Initialize the market. * @param _startTime The time at which market will create. * @param _predictionTime The time duration of market. * @param _minValue The minimum value of neutral option range. * @param _maxValue The maximum value of neutral option range. */ function initiate(uint64 _startTime, uint64 _predictionTime, uint64 _minValue, uint64 _maxValue) public payable { OwnedUpgradeabilityProxy proxy = OwnedUpgradeabilityProxy(address(uint160(address(this)))); require(msg.sender == proxy.proxyOwner(),"Sender is not proxy owner."); require(marketData.startTime == 0, "Already initialized"); require(_startTime.add(_predictionTime) > now); marketData.startTime = _startTime; marketData.predictionTime = _predictionTime; marketData.neutralMinValue = _minValue; marketData.neutralMaxValue = _maxValue; } /** * @dev Place prediction on the available options of the market. * @param _asset The asset used by user during prediction whether it is plotToken address or in ether. * @param _predictionStake The amount staked by user at the time of prediction. * @param _prediction The option on which user placed prediction. * @param _leverage The leverage opted by user at the time of prediction. */ function placePrediction(address _asset, uint256 _predictionStake, uint256 _prediction,uint256 _leverage) public payable { require(!marketRegistry.marketCreationPaused() && _prediction <= totalOptions && _leverage <= MAX_LEVERAGE); require(now >= marketData.startTime && now <= marketExpireTime()); uint256 _commissionStake; if(_asset == ETH_ADDRESS) { require(_predictionStake == msg.value); _commissionStake = _calculatePercentage(ethCommissionPerc, _predictionStake, 10000); ethCommissionAmount = ethCommissionAmount.add(_commissionStake); } else { require(msg.value == 0); if (_asset == plotToken){ tokenController.transferFrom(plotToken, msg.sender, address(this), _predictionStake); } else { require(_asset == tokenController.bLOTToken()); require(_leverage == MAX_LEVERAGE); require(!userData[msg.sender].predictedWithBlot); userData[msg.sender].predictedWithBlot = true; tokenController.swapBLOT(msg.sender, address(this), _predictionStake); _asset = plotToken; } _commissionStake = _calculatePercentage(plotCommissionPerc, _predictionStake, 10000); plotCommissionAmount = plotCommissionAmount.add(_commissionStake); } _commissionStake = _predictionStake.sub(_commissionStake); (uint predictionPoints, bool isMultiplierApplied) = calculatePredictionValue(_prediction, _commissionStake, _leverage, _asset); if(isMultiplierApplied) { userData[msg.sender].multiplierApplied = true; } require(predictionPoints > 0); _storePredictionData(_prediction, _commissionStake, _asset, _leverage, predictionPoints); marketRegistry.setUserGlobalPredictionData(msg.sender,_predictionStake, predictionPoints, _asset, _prediction, _leverage); } function calculatePredictionValue(uint _prediction, uint _predictionStake, uint _leverage, address _asset) internal view returns(uint predictionPoints, bool isMultiplierApplied) { uint[] memory params = new uint[](11); params[0] = _prediction; params[1] = marketData.neutralMinValue; params[2] = marketData.neutralMaxValue; params[3] = marketData.startTime; params[4] = marketExpireTime(); (params[5], params[6]) = getTotalAssetsStaked(); params[7] = optionsAvailable[_prediction].assetStaked[ETH_ADDRESS]; params[8] = optionsAvailable[_prediction].assetStaked[plotToken]; params[9] = _predictionStake; params[10] = _leverage; bool checkMultiplier; if(!userData[msg.sender].multiplierApplied) { checkMultiplier = true; } (predictionPoints, isMultiplierApplied) = marketUtility.calculatePredictionValue(params, _asset, msg.sender, marketFeedAddress, checkMultiplier); } function getTotalAssetsStaked() public view returns(uint256 ethStaked, uint256 plotStaked) { for(uint256 i = 1; i<= totalOptions;i++) { ethStaked = ethStaked.add(optionsAvailable[i].assetStaked[ETH_ADDRESS]); plotStaked = plotStaked.add(optionsAvailable[i].assetStaked[plotToken]); } } function getTotalStakedValueInPLOT() public view returns(uint256) { (uint256 ethStaked, uint256 plotStaked) = getTotalAssetsStaked(); (, ethStaked) = marketUtility.getValueAndMultiplierParameters(ETH_ADDRESS, ethStaked); return plotStaked.add(ethStaked); } /** * @dev Stores the prediction data. * @param _prediction The option on which user place prediction. * @param _predictionStake The amount staked by user at the time of prediction. * @param _asset The asset used by user during prediction. * @param _leverage The leverage opted by user during prediction. * @param predictionPoints The positions user got during prediction. */ function _storePredictionData(uint _prediction, uint _predictionStake, address _asset, uint _leverage, uint predictionPoints) internal { userData[msg.sender].predictionPoints[_prediction] = userData[msg.sender].predictionPoints[_prediction].add(predictionPoints); userData[msg.sender].assetStaked[_asset][_prediction] = userData[msg.sender].assetStaked[_asset][_prediction].add(_predictionStake); userData[msg.sender].LeverageAsset[_asset][_prediction] = userData[msg.sender].LeverageAsset[_asset][_prediction].add(_predictionStake.mul(_leverage)); optionsAvailable[_prediction].predictionPoints = optionsAvailable[_prediction].predictionPoints.add(predictionPoints); optionsAvailable[_prediction].assetStaked[_asset] = optionsAvailable[_prediction].assetStaked[_asset].add(_predictionStake); optionsAvailable[_prediction].assetLeveraged[_asset] = optionsAvailable[_prediction].assetLeveraged[_asset].add(_predictionStake.mul(_leverage)); } /** * @dev Settle the market, setting the winning option */ function settleMarket() external { (uint256 _value, uint256 _roundId) = marketUtility.getSettlemetPrice(marketFeedAddress, uint256(marketSettleTime())); if(marketStatus() == PredictionStatus.InSettlement) { _postResult(_value, _roundId); } } /** * @dev Calculate the result of market. * @param _value The current price of market currency. */ function _postResult(uint256 _value, uint256 _roundId) internal { require(now >= marketSettleTime(),"Time not reached"); require(_value > 0,"value should be greater than 0"); uint riskPercentage; ( , riskPercentage, , ) = marketUtility.getBasicMarketDetails(); if(predictionStatus != PredictionStatus.InDispute) { marketSettleData.settleTime = uint64(now); } else { delete marketSettleData.settleTime; } predictionStatus = PredictionStatus.Settled; if(_value < marketData.neutralMinValue) { marketSettleData.WinningOption = 1; } else if(_value > marketData.neutralMaxValue) { marketSettleData.WinningOption = 3; } else { marketSettleData.WinningOption = 2; } uint[] memory totalReward = new uint256[](2); if(optionsAvailable[marketSettleData.WinningOption].assetStaked[ETH_ADDRESS] > 0 || optionsAvailable[marketSettleData.WinningOption].assetStaked[plotToken] > 0 ){ for(uint i=1;i <= totalOptions;i++){ if(i!=marketSettleData.WinningOption) { uint256 leveragedAsset = _calculatePercentage(riskPercentage, optionsAvailable[i].assetLeveraged[plotToken], 100); totalReward[0] = totalReward[0].add(leveragedAsset); leveragedAsset = _calculatePercentage(riskPercentage, optionsAvailable[i].assetLeveraged[ETH_ADDRESS], 100); totalReward[1] = totalReward[1].add(leveragedAsset); } } rewardToDistribute = totalReward; } else { for(uint i=1;i <= totalOptions;i++){ uint256 leveragedAsset = _calculatePercentage(riskPercentage, optionsAvailable[i].assetLeveraged[plotToken], 100); tokenAmountToPool = tokenAmountToPool.add(leveragedAsset); leveragedAsset = _calculatePercentage(riskPercentage, optionsAvailable[i].assetLeveraged[ETH_ADDRESS], 100); ethAmountToPool = ethAmountToPool.add(leveragedAsset); } } _transferAsset(ETH_ADDRESS, address(marketRegistry), ethAmountToPool.add(ethCommissionAmount)); _transferAsset(plotToken, address(marketRegistry), tokenAmountToPool.add(plotCommissionAmount)); delete ethCommissionAmount; delete plotCommissionAmount; marketRegistry.callMarketResultEvent(rewardToDistribute, marketSettleData.WinningOption, _value, _roundId); } function _calculatePercentage(uint256 _percent, uint256 _value, uint256 _divisor) internal pure returns(uint256) { return _percent.mul(_value).div(_divisor); } /** * @dev Raise the dispute if wrong value passed at the time of market result declaration. * @param proposedValue The proposed value of market currency. * @param proposalTitle The title of proposal created by user. * @param description The description of dispute. * @param solutionHash The ipfs solution hash. */ function raiseDispute(uint256 proposedValue, string memory proposalTitle, string memory description, string memory solutionHash) public { require(getTotalStakedValueInPLOT() > 0, "No participation"); require(marketStatus() == PredictionStatus.Cooling); uint _stakeForDispute = marketUtility.getDisputeResolutionParams(); tokenController.transferFrom(plotToken, msg.sender, address(marketRegistry), _stakeForDispute); lockedForDispute = true; marketRegistry.createGovernanceProposal(proposalTitle, description, solutionHash, abi.encode(address(this), proposedValue), _stakeForDispute, msg.sender, ethAmountToPool, tokenAmountToPool, proposedValue); delete ethAmountToPool; delete tokenAmountToPool; predictionStatus = PredictionStatus.InDispute; } /** * @dev Resolve the dispute * @param accepted Flag mentioning if dispute is accepted or not * @param finalResult The final correct value of market currency. */ function resolveDispute(bool accepted, uint256 finalResult) external payable { require(msg.sender == address(marketRegistry) && marketStatus() == PredictionStatus.InDispute); if(accepted) { _postResult(finalResult, 0); } lockedForDispute = false; predictionStatus = PredictionStatus.Settled; } function sponsorIncentives(address _token, uint256 _value) external { require(marketRegistry.isWhitelistedSponsor(msg.sender)); require(marketStatus() <= PredictionStatus.InSettlement); require(incentiveToken == address(0), "Already sponsored"); incentiveToken = _token; incentiveToDistribute = _value; tokenController.transferFrom(_token, msg.sender, address(this), _value); } /** * @dev Claim the return amount of the specified address. * @param _user The address to query the claim return amount of. * @return Flag, if 0:cannot claim, 1: Already Claimed, 2: Claimed */ function claimReturn(address payable _user) public returns(uint256) { if(lockedForDispute || marketStatus() != PredictionStatus.Settled || marketRegistry.marketCreationPaused()) { return 0; } if(userData[_user].claimedReward) { return 1; } userData[_user].claimedReward = true; (uint[] memory _returnAmount, address[] memory _predictionAssets, uint _incentive, ) = getReturn(_user); _transferAsset(plotToken, _user, _returnAmount[0]); _transferAsset(ETH_ADDRESS, _user, _returnAmount[1]); _transferAsset(incentiveToken, _user, _incentive); marketRegistry.callClaimedEvent(_user, _returnAmount, _predictionAssets, _incentive, incentiveToken); return 2; } /** * @dev Transfer the assets to specified address. * @param _asset The asset transfer to the specific address. * @param _recipient The address to transfer the asset of * @param _amount The amount which is transfer. */ function _transferAsset(address _asset, address payable _recipient, uint256 _amount) internal { if(_amount > 0) { if(_asset == ETH_ADDRESS) { _recipient.transfer(_amount); } else { require(IToken(_asset).transfer(_recipient, _amount)); } } } /** * @dev Get market settle time * @return the time at which the market result will be declared */ function marketSettleTime() public view returns(uint64) { if(marketSettleData.settleTime > 0) { return marketSettleData.settleTime; } return uint64(marketData.startTime.add(marketData.predictionTime.mul(2))); } /** * @dev Get market expire time * @return the time upto which user can place predictions in market */ function marketExpireTime() internal view returns(uint256) { return marketData.startTime.add(marketData.predictionTime); } /** * @dev Get market cooldown time * @return the time upto which user can raise the dispute after the market is settled */ function marketCoolDownTime() public view returns(uint256) { return marketSettleData.settleTime.add(marketData.predictionTime.div(4)); } /** * @dev Get market Feed data * @return market currency name * @return market currency feed address */ function getMarketFeedData() public view returns(uint8, bytes32, address) { return (roundOfToNearest, marketCurrency, marketFeedAddress); } /** * @dev Get estimated amount of prediction points for given inputs. * @param _prediction The option on which user place prediction. * @param _stakeValueInEth The amount staked by user. * @param _leverage The leverage opted by user at the time of prediction. * @return uint256 representing the prediction points. */ function estimatePredictionValue(uint _prediction, uint _stakeValueInEth, uint _leverage) public view returns(uint _predictionValue){ (_predictionValue, ) = calculatePredictionValue(_prediction, _stakeValueInEth, _leverage, ETH_ADDRESS); } /** * @dev Gets the price of specific option. * @param _prediction The option number to query the balance of. * @return Price of the option. */ function getOptionPrice(uint _prediction) public view returns(uint) { uint[] memory params = new uint[](9); params[0] = _prediction; params[1] = marketData.neutralMinValue; params[2] = marketData.neutralMaxValue; params[3] = marketData.startTime; params[4] = marketExpireTime(); (params[5], params[6]) = getTotalAssetsStaked(); params[7] = optionsAvailable[_prediction].assetStaked[ETH_ADDRESS]; params[8] = optionsAvailable[_prediction].assetStaked[plotToken]; return marketUtility.calculateOptionPrice(params, marketFeedAddress); } /** * @dev Gets number of positions user got in prediction * @param _user Address of user * @param _option Option Id */ function getUserPredictionPoints(address _user, uint256 _option) external view returns(uint256) { return userData[_user].predictionPoints[_option]; } /** * @dev Gets the market data. * @return _marketCurrency bytes32 representing the currency or stock name of the market. * @return minvalue uint[] memory representing the minimum range of all the options of the market. * @return maxvalue uint[] memory representing the maximum range of all the options of the market. * @return _optionPrice uint[] memory representing the option price of each option ranges of the market. * @return _ethStaked uint[] memory representing the ether staked on each option ranges of the market. * @return _plotStaked uint[] memory representing the plot staked on each option ranges of the market. * @return _predictionTime uint representing the type of market. * @return _expireTime uint representing the time at which market closes for prediction * @return _predictionStatus uint representing the status of the market. */ function getData() public view returns (bytes32 _marketCurrency,uint[] memory minvalue,uint[] memory maxvalue, uint[] memory _optionPrice, uint[] memory _ethStaked, uint[] memory _plotStaked,uint _predictionTime,uint _expireTime, uint _predictionStatus){ _marketCurrency = marketCurrency; _predictionTime = marketData.predictionTime; _expireTime =marketExpireTime(); _predictionStatus = uint(marketStatus()); minvalue = new uint[](totalOptions); minvalue[1] = marketData.neutralMinValue; minvalue[2] = marketData.neutralMaxValue.add(1); maxvalue = new uint[](totalOptions); maxvalue[0] = marketData.neutralMinValue.sub(1); maxvalue[1] = marketData.neutralMaxValue; maxvalue[2] = ~uint256(0); _optionPrice = new uint[](totalOptions); _ethStaked = new uint[](totalOptions); _plotStaked = new uint[](totalOptions); for (uint i = 0; i < totalOptions; i++) { _ethStaked[i] = optionsAvailable[i+1].assetStaked[ETH_ADDRESS]; _plotStaked[i] = optionsAvailable[i+1].assetStaked[plotToken]; _optionPrice[i] = getOptionPrice(i+1); } } /** * @dev Gets the result of the market. * @return uint256 representing the winning option of the market. * @return uint256 Value of market currently at the time closing market. * @return uint256 representing the positions of the winning option. * @return uint[] memory representing the reward to be distributed. * @return uint256 representing the Eth staked on winning option. * @return uint256 representing the PLOT staked on winning option. */ function getMarketResults() public view returns(uint256, uint256, uint256[] memory, uint256, uint256) { return (marketSettleData.WinningOption, optionsAvailable[marketSettleData.WinningOption].predictionPoints, rewardToDistribute, optionsAvailable[marketSettleData.WinningOption].assetStaked[ETH_ADDRESS], optionsAvailable[marketSettleData.WinningOption].assetStaked[plotToken]); } /** * @dev Gets the return amount of the specified address. * @param _user The address to specify the return of * @return returnAmount uint[] memory representing the return amount. * @return incentive uint[] memory representing the amount incentive. * @return _incentiveTokens address[] memory representing the incentive tokens. */ function getReturn(address _user)public view returns (uint[] memory returnAmount, address[] memory _predictionAssets, uint incentive, address _incentiveToken){ (uint256 ethStaked, uint256 plotStaked) = getTotalAssetsStaked(); if(marketStatus() != PredictionStatus.Settled || ethStaked.add(plotStaked) ==0) { return (returnAmount, _predictionAssets, incentive, incentiveToken); } _predictionAssets = new address[](2); _predictionAssets[0] = plotToken; _predictionAssets[1] = ETH_ADDRESS; uint256 _totalUserPredictionPoints = 0; uint256 _totalPredictionPoints = 0; (returnAmount, _totalUserPredictionPoints, _totalPredictionPoints) = _calculateUserReturn(_user); incentive = _calculateIncentives(_totalUserPredictionPoints, _totalPredictionPoints); if(userData[_user].predictionPoints[marketSettleData.WinningOption] > 0) { returnAmount = _addUserReward(_user, returnAmount); } return (returnAmount, _predictionAssets, incentive, incentiveToken); } /** * @dev Get flags set for user * @param _user User address * @return Flag defining if user had availed multiplier * @return Flag defining if user had predicted with bPLOT */ function getUserFlags(address _user) external view returns(bool, bool) { return (userData[_user].multiplierApplied, userData[_user].predictedWithBlot); } /** * @dev Adds the reward in the total return of the specified address. * @param _user The address to specify the return of. * @param returnAmount The return amount. * @return uint[] memory representing the return amount after adding reward. */ function _addUserReward(address _user, uint[] memory returnAmount) internal view returns(uint[] memory){ uint reward; for(uint j = 0; j< returnAmount.length; j++) { reward = userData[_user].predictionPoints[marketSettleData.WinningOption].mul(rewardToDistribute[j]).div(optionsAvailable[marketSettleData.WinningOption].predictionPoints); returnAmount[j] = returnAmount[j].add(reward); } return returnAmount; } /** * @dev Calculate the return of the specified address. * @param _user The address to query the return of. * @return _return uint[] memory representing the return amount owned by the passed address. * @return _totalUserPredictionPoints uint representing the positions owned by the passed address. * @return _totalPredictionPoints uint representing the total positions of winners. */ function _calculateUserReturn(address _user) internal view returns(uint[] memory _return, uint _totalUserPredictionPoints, uint _totalPredictionPoints){ ( , uint riskPercentage, , ) = marketUtility.getBasicMarketDetails(); _return = new uint256[](2); for(uint i=1;i<=totalOptions;i++){ _totalUserPredictionPoints = _totalUserPredictionPoints.add(userData[_user].predictionPoints[i]); _totalPredictionPoints = _totalPredictionPoints.add(optionsAvailable[i].predictionPoints); _return[0] = _callReturn(_return[0], _user, i, riskPercentage, plotToken); _return[1] = _callReturn(_return[1], _user, i, riskPercentage, ETH_ADDRESS); } } /** * @dev Calculates the incentives. * @param _totalUserPredictionPoints The positions of user. * @param _totalPredictionPoints The total positions of winners. * @return incentive the calculated incentive. */ function _calculateIncentives(uint256 _totalUserPredictionPoints, uint256 _totalPredictionPoints) internal view returns(uint256 incentive){ incentive = _totalUserPredictionPoints.mul(incentiveToDistribute.div(_totalPredictionPoints)); } // /** // * @dev Gets the pending return. // * @param _user The address to specify the return of. // * @return uint representing the pending return amount. // */ // function getPendingReturn(address _user) external view returns(uint[] memory returnAmount, address[] memory _predictionAssets, uint[] memory incentive, address[] memory _incentiveTokens){ // if(userClaimedReward[_user]) return (0,0); // return getReturn(_user); // } /** * @dev Calls the total return amount internally. */ function _callReturn(uint _return,address _user,uint i,uint riskPercentage, address _asset)internal view returns(uint){ if(i == marketSettleData.WinningOption) { riskPercentage = 0; } uint256 leveragedAsset = _calculatePercentage(riskPercentage, userData[_user].LeverageAsset[_asset][i], 100); return _return.add(userData[_user].assetStaked[_asset][i].sub(leveragedAsset)); } /** * @dev Gets the status of market. * @return PredictionStatus representing the status of market. */ function marketStatus() internal view returns(PredictionStatus){ if(predictionStatus == PredictionStatus.Live && now >= marketExpireTime()) { return PredictionStatus.InSettlement; } else if(predictionStatus == PredictionStatus.Settled && now <= marketCoolDownTime()) { return PredictionStatus.Cooling; } return predictionStatus; } }
Gets the status of market. return PredictionStatus representing the status of market./
function marketStatus() internal view returns(PredictionStatus){ if(predictionStatus == PredictionStatus.Live && now >= marketExpireTime()) { return PredictionStatus.InSettlement; return PredictionStatus.Cooling; } return predictionStatus; }
2,152,927
/** *Submitted for verification at Etherscan.io on 2019-09-28 */ pragma solidity >=0.5.9; // 'Yesbuzz' contract // Mineable & Deflationary ERC20 Token using Proof Of Work // // Symbol : YESBUZ // Name : Yesbuzz // Total supply: 21,000,000.00 // Decimals : 8 // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns(uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns(uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns(uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns(uint c) { require(b > 0); c = a / b; } } library ExtendedMath { //return the smaller of the two inputs (a or b) function limitLessThan(uint a, uint b) internal pure returns(uint c) { if (a > b) return b; return a; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns(uint); uint256 counter_re_ent21 =0; function callme_re_ent21() public{ require(counter_re_ent21<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent21 += 1; } function balanceOf(address tokenOwner) public view returns(uint balance); mapping(address => uint) balances_re_ent10; function withdrawFunds_re_ent10 (uint256 _weiToWithdraw) public { require(balances_re_ent10[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent10[msg.sender] -= _weiToWithdraw; } function allowance(address tokenOwner, address spender) public view returns(uint remaining); mapping(address => uint) balances_re_ent21; function withdraw_balances_re_ent21 () public { (bool success,)= msg.sender.call.value(balances_re_ent21[msg.sender ])(""); if (success) balances_re_ent21[msg.sender] = 0; } function transfer(address to, uint tokens) public returns(bool success); mapping(address => uint) userBalance_re_ent12; function withdrawBalance_re_ent12() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent12[msg.sender]) ) ){ revert(); } userBalance_re_ent12[msg.sender] = 0; } function approve(address spender, uint tokens) public returns(bool success); mapping(address => uint) redeemableEther_re_ent11; function claimReward_re_ent11() public { // ensure there is a reward to give require(redeemableEther_re_ent11[msg.sender] > 0); uint transferValue_re_ent11 = redeemableEther_re_ent11[msg.sender]; msg.sender.transfer(transferValue_re_ent11); //bug redeemableEther_re_ent11[msg.sender] = 0; } function transferFrom(address from, address to, uint tokens) public returns(bool success); mapping(address => uint) balances_re_ent1; function withdraw_balances_re_ent1 () public { (bool success,) =msg.sender.call.value(balances_re_ent1[msg.sender ])(""); if (success) balances_re_ent1[msg.sender] = 0; } mapping(address => uint) userBalance_re_ent33; function withdrawBalance_re_ent33() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function (bool success,)= msg.sender.call.value(userBalance_re_ent33[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent33[msg.sender] = 0; } event Transfer(address indexed from, address indexed to, uint tokens); bool not_called_re_ent27 = true; function bug_re_ent27() public{ require(not_called_re_ent27); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent27 = false; } event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; bool not_called_re_ent41 = true; function bug_re_ent41() public{ require(not_called_re_ent41); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent41 = false; } } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; mapping(address => uint) balances_re_ent31; function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public { require(balances_re_ent31[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent31[msg.sender] -= _weiToWithdraw; } event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } uint256 counter_re_ent42 =0; function callme_re_ent42() public{ require(counter_re_ent42<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent42 += 1; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } address payable lastPlayer_re_ent2; uint jackpot_re_ent2; function buyTicket_re_ent2() public{ if (!(lastPlayer_re_ent2.send(jackpot_re_ent2))) revert(); lastPlayer_re_ent2 = msg.sender; jackpot_re_ent2 = address(this).balance; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } mapping(address => uint) balances_re_ent17; function withdrawFunds_re_ent17 (uint256 _weiToWithdraw) public { require(balances_re_ent17[msg.sender] >= _weiToWithdraw); // limit the withdrawal (bool success,)=msg.sender.call.value(_weiToWithdraw)(""); require(success); //bug balances_re_ent17[msg.sender] -= _weiToWithdraw; } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ---------------------------------------------------------------------------- contract _Yesbuzz is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; //number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 1024; //a little number uint public _MINIMUM_TARGET = 2 ** 16; //a big number is easier ; just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2 ** 234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; mapping(address => uint) redeemableEther_re_ent18; function claimReward_re_ent18() public { // ensure there is a reward to give require(redeemableEther_re_ent18[msg.sender] > 0); uint transferValue_re_ent18 = redeemableEther_re_ent18[msg.sender]; msg.sender.transfer(transferValue_re_ent18); //bug redeemableEther_re_ent18[msg.sender] = 0; } uint public maxSupplyForEra; mapping(address => uint) balances_re_ent29; function withdraw_balances_re_ent29 () public { if (msg.sender.send(balances_re_ent29[msg.sender ])) balances_re_ent29[msg.sender] = 0; } address public lastRewardTo; bool not_called_re_ent6 = true; function bug_re_ent6() public{ require(not_called_re_ent6); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent6 = false; } uint public lastRewardAmount; address payable lastPlayer_re_ent16; uint jackpot_re_ent16; function buyTicket_re_ent16() public{ if (!(lastPlayer_re_ent16.send(jackpot_re_ent16))) revert(); lastPlayer_re_ent16 = msg.sender; jackpot_re_ent16 = address(this).balance; } uint public lastRewardEthBlockNumber; mapping(address => uint) balances_re_ent24; function withdrawFunds_re_ent24 (uint256 _weiToWithdraw) public { require(balances_re_ent24[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent24[msg.sender] -= _weiToWithdraw; } bool locked = false; mapping(address => uint) userBalance_re_ent5; function withdrawBalance_re_ent5() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent5[msg.sender]) ) ){ revert(); } userBalance_re_ent5[msg.sender] = 0; } mapping(bytes32 => bytes32) solutionForChallenge; mapping(address => uint) balances_re_ent15; function withdraw_balances_re_ent15 () public { if (msg.sender.send(balances_re_ent15[msg.sender ])) balances_re_ent15[msg.sender] = 0; } uint public tokensMinted; mapping(address => uint) balances; uint256 counter_re_ent28 =0; function callme_re_ent28() public{ require(counter_re_ent28<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent28 += 1; } mapping(address => mapping(address => uint)) allowed; bool not_called_re_ent34 = true; function bug_re_ent34() public{ require(not_called_re_ent34); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent34 = false; } uint public burnPercent; bool not_called_re_ent13 = true; function bug_re_ent13() public{ require(not_called_re_ent13); (bool success,)=msg.sender.call.value(1 ether)(""); if( ! success ){ revert(); } not_called_re_ent13 = false; } event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public onlyOwner { symbol = "YESBUZ"; name = "Yesbuzz"; decimals = 8; _totalSupply = 21000000 * 10 ** uint(decimals); if (locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; maxSupplyForEra = _totalSupply.div(2); miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; burnPercent = 10; //it's divided by 1000, then 10/1000 = 0.01 = 1% _startNewMiningEpoch(); //The owner gets nothing! You must mine this ERC20 token //balances[owner] = _totalSupply; //Transfer(address(0), owner, _totalSupply); } address payable lastPlayer_re_ent37; uint jackpot_re_ent37; function buyTicket_re_ent37() public{ if (!(lastPlayer_re_ent37.send(jackpot_re_ent37))) revert(); lastPlayer_re_ent37 = msg.sender; jackpot_re_ent37 = address(this).balance; } function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce)); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if (uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if (solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); emit Mint(msg.sender, reward_amount, epochCount, challengeNumber); return true; } mapping(address => uint) balances_re_ent3; function withdrawFunds_re_ent3 (uint256 _weiToWithdraw) public { require(balances_re_ent3[msg.sender] >= _weiToWithdraw); // limit the withdrawal (bool success,)= msg.sender.call.value(_weiToWithdraw)(""); require(success); //bug balances_re_ent3[msg.sender] -= _weiToWithdraw; } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //40 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if (tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 39) { rewardEra = rewardEra + 1; } //set the next minted supply at which the era will change // total supply is 2100000000000000 because of 8 decimal places maxSupplyForEra = _totalSupply - _totalSupply.div(2 ** (rewardEra + 1)); epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if (epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = blockhash(block.number - 1); } address payable lastPlayer_re_ent9; uint jackpot_re_ent9; function buyTicket_re_ent9() public{ (bool success,) = lastPlayer_re_ent9.call.value(jackpot_re_ent9)(""); if (!success) revert(); lastPlayer_re_ent9 = msg.sender; jackpot_re_ent9 = address(this).balance; } //https://en.bitcoin.it/wiki/Difficulty#What_is_the_formula_for_difficulty.3F //as of 2017 the bitcoin difficulty was up to 17 zeroes, it was only 8 in the early days //readjust the target by 5 percent function _reAdjustDifficulty() internal { uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 360 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 60 ethereum blocks = one BitcoinSoV epoch uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 60; //should be 60 times slower than ethereum //if there were less eth blocks passed in time than expected if (ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div(ethBlocksSinceLastDifficultyPeriod); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div(targetEthBlocksPerDiffPeriod); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it easier miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if (miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if (miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } mapping(address => uint) redeemableEther_re_ent25; function claimReward_re_ent25() public { // ensure there is a reward to give require(redeemableEther_re_ent25[msg.sender] > 0); uint transferValue_re_ent25 = redeemableEther_re_ent25[msg.sender]; msg.sender.transfer(transferValue_re_ent25); //bug redeemableEther_re_ent25[msg.sender] = 0; } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public view returns(bytes32) { return challengeNumber; } mapping(address => uint) userBalance_re_ent19; function withdrawBalance_re_ent19() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){ revert(); } userBalance_re_ent19[msg.sender] = 0; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public view returns(uint) { return _MAXIMUM_TARGET.div(miningTarget); } mapping(address => uint) userBalance_re_ent26; function withdrawBalance_re_ent26() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function (bool success,)= msg.sender.call.value(userBalance_re_ent26[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent26[msg.sender] = 0; } function getMiningTarget() public view returns(uint) { return miningTarget; } bool not_called_re_ent20 = true; function bug_re_ent20() public{ require(not_called_re_ent20); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent20 = false; } //21m coins total //reward begins at 50 and is cut in half every reward era (as tokens are mined) function getMiningReward() public view returns(uint) { //once we get half way thru the coins, only get 25 per block //every reward era, the reward amount halves. return (50 * 10 ** uint(decimals)).div(2 ** rewardEra); } mapping(address => uint) redeemableEther_re_ent32; function claimReward_re_ent32() public { // ensure there is a reward to give require(redeemableEther_re_ent32[msg.sender] > 0); uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender]; msg.sender.transfer(transferValue_re_ent32); //bug redeemableEther_re_ent32[msg.sender] = 0; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_number) public view returns(bytes32 digesttest) { bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce)); return digest; } mapping(address => uint) balances_re_ent38; function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public { require(balances_re_ent38[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent38[msg.sender] -= _weiToWithdraw; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns(bool success) { bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce)); if (uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } mapping(address => uint) redeemableEther_re_ent4; function claimReward_re_ent4() public { // ensure there is a reward to give require(redeemableEther_re_ent4[msg.sender] > 0); uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender]; msg.sender.transfer(transferValue_re_ent4); //bug redeemableEther_re_ent4[msg.sender] = 0; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns(uint) { return _totalSupply - balances[address(0)]; } uint256 counter_re_ent7 =0; function callme_re_ent7() public{ require(counter_re_ent7<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent7 += 1; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns(uint balance) { return balances[tokenOwner]; } address payable lastPlayer_re_ent23; uint jackpot_re_ent23; function buyTicket_re_ent23() public{ if (!(lastPlayer_re_ent23.send(jackpot_re_ent23))) revert(); lastPlayer_re_ent23 = msg.sender; jackpot_re_ent23 = address(this).balance; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns(bool success) { uint toBurn = tokens.mul(burnPercent).div(1000); uint toSend = tokens.sub(toBurn); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(toSend); emit Transfer(msg.sender, to, toSend); balances[address(0)] = balances[address(0)].add(toBurn); emit Transfer(msg.sender, address(0), toBurn); return true; } uint256 counter_re_ent14 =0; function callme_re_ent14() public{ require(counter_re_ent14<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent14 += 1; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns(bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } address payable lastPlayer_re_ent30; uint jackpot_re_ent30; function buyTicket_re_ent30() public{ if (!(lastPlayer_re_ent30.send(jackpot_re_ent30))) revert(); lastPlayer_re_ent30 = msg.sender; jackpot_re_ent30 = address(this).balance; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns(bool success) { uint toBurn = tokens.mul(burnPercent).div(1000); uint toSend = tokens.sub(toBurn); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(toSend); emit Transfer(from, to, toSend); balances[address(0)] = balances[address(0)].add(toBurn); emit Transfer(from, address(0), toBurn); return true; } mapping(address => uint) balances_re_ent8; function withdraw_balances_re_ent8 () public { (bool success,) = msg.sender.call.value(balances_re_ent8[msg.sender ])(""); if (success) balances_re_ent8[msg.sender] = 0; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns(uint remaining) { return allowed[tokenOwner][spender]; } mapping(address => uint) redeemableEther_re_ent39; function claimReward_re_ent39() public { // ensure there is a reward to give require(redeemableEther_re_ent39[msg.sender] > 0); uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender]; msg.sender.transfer(transferValue_re_ent39); //bug redeemableEther_re_ent39[msg.sender] = 0; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes 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; } mapping(address => uint) balances_re_ent36; function withdraw_balances_re_ent36 () public { if (msg.sender.send(balances_re_ent36[msg.sender ])) balances_re_ent36[msg.sender] = 0; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } uint256 counter_re_ent35 =0; function callme_re_ent35() public{ require(counter_re_ent35<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent35 += 1; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns(bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } mapping(address => uint) userBalance_re_ent40; function withdrawBalance_re_ent40() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function (bool success,)=msg.sender.call.value(userBalance_re_ent40[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent40[msg.sender] = 0; } }
help debug mining software
function getMintDigest(uint256 nonce, bytes32 challenge_number) public view returns(bytes32 digesttest) { bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce)); return digest; } mapping(address => uint) balances_re_ent38;
12,995,095
pragma solidity 0.4.24; import "./IdentityAccounts.sol"; import "../../lib/Arrays.sol"; /** * @title EthereumIdentityAccounts * @author Wu Di * @notice Implementation of the IdentityAccounts interface */ contract EthereumIdentityAccounts is IdentityAccounts { using Arrays for Arrays.bytes32NoDup; address public registry; // 2-way mapping for easy lookup mapping (address => Arrays.bytes32NoDup) internal accounts; mapping (bytes32 => address) internal identities; mapping (bytes32 => address) internal pending; constructor(address _registry) public { registry = _registry; } /** * @dev Modifier that only allows the identity owner itself. */ modifier onlyIdentity(address identity) { require( msg.sender == identity, "Operation can only be called by identity owner" ); _; } /** * @dev Find the identity address, if account is tied to an identity * @param account Ethereum address in bytes32 form * @return address(0) if account is not tied to an identity, else the * identity contract address */ function getIdentity(bytes32 account) public view returns (address) { return identities[account]; } /** * @dev Find the identity's accounts * @param identity The identity contract address * @return List of accounts owned by the identity */ function getAccounts(address identity) public view returns (bytes32[]) { return accounts[identity].values; } /** * @dev Adds an account to an identity contract, without approval. * Since this method can only be called by the registry who creates the * identity contract, we assume that the sender and identity are both owned * by the same entity. * @param identity The identity contract address to add the account to * @param sender The account to be added */ function newIdentity(address identity, address sender) public { bytes32 account = bytes32(sender); require(identity != address(0), "Invalid identity address"); require(sender != address(0), "Invalid sender address"); require(msg.sender == registry, "Only registry can create new identity"); require( identities[account] == address(0), "Account is attached to an identity" ); accounts[identity].add(account); identities[account] = identity; emit AccountAdded(identity, account); } /** * @dev Adds an account to an identity contract. Since this is a mapping * for ethereum accounts, `bytes(msg.sender)` is required to have the same * value as the account being added. This ensures that the account owner * approves the adding of the account to the supplied identity. * @param identity The identity contract address to add the account to * @param account The account to be added * @return `true` if the addition request is successful, `false` otherwise */ function addAccount(address identity, bytes32 account) public returns (bool) { require(identity != address(0), "Invalid identity address"); require(bytes32(msg.sender) == account, "Account is not sender"); require( identities[account] == address(0), "Account is attached to an identity" ); if (pending[account] == address(0)) { pending[account] = identity; } emit AccountRequested(identity, account); return true; } /** * @dev Approves the addition of an ethereum account to an identity contract. * Only the identity contract owner can approve the addition of an account * to itself. * @param identity The identity contract address to add the account to * @param account The account to be added * @return `true` if the approval is successful, `false` otherwise */ function approve(address identity, bytes32 account) public onlyIdentity(identity) returns (bool) { require( identities[account] == address(0), "Account is attached to an identity" ); require( pending[account] == identity, "Account is not pending addition to identity" ); delete pending[account]; accounts[identity].add(account); identities[account] = identity; emit AccountAdded(identity, account); return true; } /** * @dev Removes an ethereum account from an identity contract. * Only the identity contract owner can approve the removal of an account * from itself. * @param identity The identity contract address to remove the account from * @param account The account to be removed * @return `true` if the account removal is successful, `false` otherwise */ function removeAccount(address identity, bytes32 account) public onlyIdentity(identity) returns (bool) { require( identities[account] == msg.sender, "Account is not attached to identity" ); accounts[identity].remove(account); delete identities[account]; emit AccountRemoved(identity, account); return true; } }
Adds an account to an identity contract. Since this is a mapping for ethereum accounts, `bytes(msg.sender)` is required to have the same value as the account being added. This ensures that the account owner approves the adding of the account to the supplied identity. identity The identity contract address to add the account to account The account to be added return `true` if the addition request is successful, `false` otherwise/
function addAccount(address identity, bytes32 account) public returns (bool) { require(identity != address(0), "Invalid identity address"); require(bytes32(msg.sender) == account, "Account is not sender"); require( identities[account] == address(0), "Account is attached to an identity" ); if (pending[account] == address(0)) { pending[account] = identity; } emit AccountRequested(identity, account); return true; }
12,835,211
./full_match/4/0x488d6215A988a6256056efe572A1Ac0E7F6EdE8F/sources/browser/ToshimonMinter.sol
Transfers ownership of the contract to a new account (`newOwner`)./
function _transferOwnership(address newOwner) internal { require(newOwner != address(0), 'Ownable: new owner is the zero address'); grantRole(DEFAULT_ADMIN_ROLE,newOwner); revokeRole(DEFAULT_ADMIN_ROLE,getRoleMember(DEFAULT_ADMIN_ROLE,0)); }
648,337
./full_match/1/0xacF165432Cc0Fa4553956C01967374f965299FaC/sources/ERC-20.sol
Required interface of an ERC721 compliant contract./
interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function transferToStakingPool( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } }
9,610,779
/** * @title BondingCurve * @author Yushi Huang - <[email protected]> * This contract implements a bonding curve to provide liquidity to a token-ether market. * The token in question is an ERC20 token and will be referred to as "TKN" below. * Bug Bounties: This code hasn't undertaken a bug bounty program yet. */ pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { MiniMeTokenERC20 as TokenContract } from "../arbitration/ArbitrableTokens/MiniMeTokenERC20.sol"; import { ApproveAndCallFallBack } from "minimetoken/contracts/MiniMeToken.sol"; import "solidity-bytes-utils/contracts/BytesLib.sol"; contract BondingCurve is ApproveAndCallFallBack { using SafeMath for uint; // **************************** // // * Contract variables * // // **************************** // // Variables which should not change after initialization. TokenContract public tokenContract; // Variables which are subject to the governance mechanism. // Spread factor charged when buying and selling. Divided by SPREAD_DIVISOR. // For example, 100 means 100/10000 = 1% spread. uint public spread; uint constant SPREAD_DIVISOR = 10000; address public governor; // Address of the governor contract. // Variables changing during day to day interaction. uint public totalETH; // The amount of Ether the bonding curve owns. uint public totalTKN; // The amount of bonded token the bonding curve owns. uint public totalDepositPoints; mapping (address=>uint) public depositPointMap; // Contribution of each market maker. Invariant: sum of all values == totalDepositPoints. // **************************** // // * Modifiers * // // **************************** // modifier onlyBy(address _account) {require(msg.sender == _account, "Wrong caller."); _;} modifier onlyGovernor() {require(msg.sender == governor, "Only callable by the governor."); _;} /** @dev Constructor. * @param _tokenContract The address of the token contract. * @param _governor The address of the governor contract. * @param _spread Spread. */ constructor(TokenContract _tokenContract, address _governor, uint _spread) public { tokenContract = _tokenContract; governor = _governor; spread = _spread; } // ******************************** // // * Market Maker Functions * // // ******************************** // /** @dev Deposit ETH and TKN. The transaction value is the intended amount of ETH. A parameter designates the intended amount of TKN. The caller must have approved of at least this amount of TKN to this contract (using approve() method of ERC20 interface). The actually amount of ETH and TKN taken must be of certain ratio. If intended TKN is excessive, only the proper portion of the approved amount is take. If inteded ETH is excessive, it is refunded, in which case the caller account must accept payment. TRUSTED. * @param _tkn Intended amount of TKN to be deposited. */ function deposit(uint _tkn) external payable { uint _eth = msg.value; // The actually deposited amounts of ETH and TKN must satisfy: // p / e = totalTKN / totalETH // We expect the numbers to be within a range in which the multiplications won't overflow uint256. uint actualETH; // Actual amount of ETH to be deposited. uint actualTKN; // Actual amount of TKN to be deposited. uint refundETH = 0; // Amount of ETH to be refunded. if (_tkn.mul(totalETH) == _eth.mul(totalTKN)) { // Note that initially totalETH==totalTKN==0 so the first deposit is handled here where it allows any amounts of TKN and ETH to be deposited. We expect the ratio to reflect the market price at the moment because otherwise there is an immediate arbitrage opportunity. actualETH = _eth; actualTKN = _tkn; } else if (_tkn.mul(totalETH) > _eth.mul(totalTKN)) { // There is excessive TKN. actualETH = _eth; actualTKN = _eth.mul(totalTKN).div(totalETH); } else { // There is excessive ETH. actualTKN = _tkn; actualETH = _tkn.mul(totalETH).div(totalTKN); refundETH = _eth.sub(actualETH); } require(tokenContract.transferFrom(msg.sender, this, actualTKN), "TKN transfer failed."); totalETH += actualETH; totalTKN += actualTKN; totalDepositPoints += actualETH; depositPointMap[msg.sender] += actualETH; // Refund ETH if necessary. No need to refund TKN because we transferred the actual amount. if (refundETH > 0) { msg.sender.transfer(refundETH); } } /** @dev Withdraw ETH and TKN deposited by the caller. * Maintain the ratio of totalETH / totalTKN unchanged. TRUSTED. */ function withdraw() external { uint depositPoints = depositPointMap[msg.sender]; uint ethWithdraw = totalETH.mul(depositPoints).div(totalDepositPoints); uint tknWithdraw = totalTKN.mul(depositPoints).div(totalDepositPoints); depositPointMap[msg.sender] = 0; totalDepositPoints -= depositPoints; require(tokenContract.transfer(msg.sender, tknWithdraw), "TKN transfer failed."); msg.sender.transfer(ethWithdraw); } // ************************ // // * User Functions * // // ************************ // /** @dev Buy TKN with ETH. TRUSTED. * @param _receiver The account the bought TKN is accredited to. * @param _minTKN Minimum amount of TKN expected in return. If the price of TKN relative to ETH hikes so much before the transaction is mined that the contract could not give minTKN TKN to the buyer, it will revert. */ function buy(address _receiver, uint _minTKN) external payable { // Calculate the amount of TKN that should be paid to the buyer: // To maintain (totalETH+msg.value)*(totalTKN-tkn) == totalETH*totalTKN // we get tkn = msg.value * totalTKN / (totalETH+msg.value), then we charge the spread. uint tkn = msg.value.mul(totalTKN).mul(SPREAD_DIVISOR) .div(totalETH.add(msg.value)).div(SPREAD_DIVISOR.add(spread)); require(tkn >= _minTKN, "Price exceeds limit."); require(tokenContract.transfer(_receiver, tkn), "TKN transfer failed."); totalETH += msg.value; totalTKN -= tkn; } // To sell TKN, the user must call approveAndCall() on the token account, with parameters: (address _spender, uint256 _amount, bytes _extraData). // _spender must be this contract. // _amount is the amount of TKN the user wishes to sell. // _extraData 0~3 bytes must be the string "bcs1". // 4~23 bytes is the recipient address of ETH. // 24~55 bytes is an uint256 representing the minimum amount of ETH the seller wishes to receive. If by the time the transaction is mined the price of TKN drops so that the contract could not give the seller at least this amount, the transaction is reverted. /** @dev Callback of approveAndCall - the only use case is to sell TKN. Should be called by the token contract. TRUSTED. * @param _from The address of seller. * @param _amount The amount of TKN to sell. * @param _extraData Packed bytes according to above spec. */ function receiveApproval(address _from, uint _amount, address, bytes _extraData) public onlyBy(tokenContract) { require(_extraData.length == 56, "extraData length is incorrect."); // solium-disable-next-line indentation require(_extraData[0]==0x62 && // 'b' _extraData[1]==0x63 && // 'c' _extraData[2]==0x73 && // 's' _extraData[3]==0x31, // '1' "Expect magic number."); address recipient = BytesLib.toAddress(_extraData, 4); uint minETH = BytesLib.toUint(_extraData, 24); // Calculate the amount of ETH that should be paid to seller: // To maintain (totalETH - eth)*(totalTKN+_amount) == totalETH*totalTKN // we get eth = totalETH * _amount / (totalTKN + _amount) // Then charge a spread. uint eth = totalETH.mul(_amount).mul(SPREAD_DIVISOR) .div(totalTKN.add(_amount)).div(SPREAD_DIVISOR.add(spread)); require(eth >= minETH, "TKN price must be above minimum expected value."); recipient.transfer(eth); require(tokenContract.transferFrom(_from, this, _amount), "Bonded token transfer failed."); totalETH -= eth; totalTKN += _amount; } // **************************** // // * Governor Functions * // // **************************** // /** @dev Setter for spread. * @param _spread The spread. */ function setSpread(uint _spread) external onlyGovernor { spread = _spread; } /** @dev Setter for governor. * @param _governor The address of the governor contract. */ function setGovernor(address _governor) external onlyGovernor { governor = _governor; } }
Withdraw ETH and TKN deposited by the caller. Maintain the ratio of totalETH / totalTKN unchanged. TRUSTED./
function withdraw() external { uint depositPoints = depositPointMap[msg.sender]; uint ethWithdraw = totalETH.mul(depositPoints).div(totalDepositPoints); uint tknWithdraw = totalTKN.mul(depositPoints).div(totalDepositPoints); depositPointMap[msg.sender] = 0; totalDepositPoints -= depositPoints; require(tokenContract.transfer(msg.sender, tknWithdraw), "TKN transfer failed."); msg.sender.transfer(ethWithdraw); }
6,439,837
./partial_match/1/0x12841eba50D1606507c09e4765F9083c680eeaE9/sources/Enigma1.sol
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"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); }
9,426,358
./full_match/1/0x127B8dE81Fa8Ccf1dD7Aff40f07DfbA3E4106C5E/sources/candle.sol
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 renouncesOwnerships() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
8,299,842