file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
./full_match/1/0xB97b945fC11046984d18E1298BECD3c82C385055/sources/contracts/WDE.sol
Set initial fees to 2.99% buy and 99% sell
setFees(0.0299e18, 0.99e18);
8,460,626
[ 1, 694, 2172, 1656, 281, 358, 576, 18, 2733, 9, 30143, 471, 14605, 9, 357, 80, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 444, 2954, 281, 12, 20, 18, 3103, 2733, 73, 2643, 16, 374, 18, 2733, 73, 2643, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract BorrowToken is ERC721URIStorage, ERC721Enumerable, Ownable, ERC721Burnable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; string public prefix = "http://app.kyoko.finance/btoken/"; string public suffix = ".png"; constructor() ERC721("KyokoBToken", "KB") {} function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, amount); } function mint(address player) public onlyOwner returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); string memory _index = uint2str(newItemId); string memory _URI = strConcat(prefix, _index, suffix); _mint(player, newItemId); _setTokenURI(newItemId, _URI); return newItemId; } function burn(uint256 tokenId) public virtual override(ERC721Burnable) { super._burn(tokenId); } function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function uint2str(uint256 _i) public pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } function strConcat( string memory _a, string memory _b, string memory _c ) public pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); string memory ret = new string(_ba.length + _bb.length + _bc.length); bytes memory bret = bytes(ret); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i++) bret[k++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i++) bret[k++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i++) bret[k++] = _bc[i]; return string(ret); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./BorrowToken.sol"; import "./LenderToken.sol"; contract Kyoko is Ownable, ERC721Holder { using SafeMath for uint256; using SafeERC20 for IERC20; BorrowToken public bToken; // bToken LenderToken public lToken; // lToken // If true, any operation will be rejected bool public pause = false; // fixed interestRate: 12%, perBlock 15s, month 30 days, year 12 months, preBlock interestRate = 0.12 * 10**18 / (Seconds * Minutes * Hours * Days * Months / perBlockTime(15s) ) uint256 public interestRate = 57870370371; uint256 public cycle = 90 days; // Minimum borrowing cycle uint256 public emergencyCycle = 30 days; // Minimum emergency cycle uint256 public fee = 50; // admin fee IERC20[] public whiteList; // whiteList struct MARK { bool isBorrow; // has borrow erc20 bool isRepay; // has repay erc20 bool hasWithdraw; // This nft has withdraw } struct Nft { address holder; // nft holder uint256 tokenId; // nft tokenId IERC721 nftToken; // nft address uint256 amount; // debt amount IERC20 erc20Token; // debt token address uint256 bTokenId; // btoken id uint256 lTokenId; // ltoken id uint256 borrowBlock; // borrow block number uint256 borrowTimestamp; // borrow timestamp uint256 emergencyTimestamp; // emergency timestamp uint256 repayAmount; // repayAmount MARK marks; } IERC721[] public NftAdrList; mapping(IERC721 => Nft[]) public NftMap; // Collaterals mapping // received collateral event NFTReceived( address operator, address from, uint256 tokenId, bytes data ); // deposit collateral event DepositErc721( uint256 _tokenId, IERC721 _nftToken, uint256 _amount, IERC20 _erc20Token ); // lend erc20 event LendERC20( uint256 _tokenId, IERC721 _nftToken, uint256 _amount, IERC20 _erc20Token, uint256 _bTokenId ); // borrow erc20 event Borrow( uint256 _tokenId, IERC721 _nftToken, uint256 _amount, IERC20 _erc20Token, uint256 _bTokenId ); // repay erc20 event Repay( uint256 _tokenId, IERC721 _nftToken, uint256 _amount, IERC20 _erc20Token, uint256 _bTokenId ); // Claim collateral event ClaimCollateral( uint256 _tokenId, IERC721 _nftToken, IERC20 _erc20Token, uint256 _bTokenId ); // LToken claim erc20 token event LTokenClaimERC20( uint256 _tokenId, IERC721 _nftToken, uint256 _amount, IERC20 _erc20Token, uint256 _lenderNftTokenId, uint256 _bTokenId ); // execute emergency to warning holder event ExecuteEmergency( uint256 _tokenId, IERC721 _nftToken, IERC20 _erc20Token, uint256 _lenderNftTokenId, uint256 _bTokenId ); // Liquidate collateral event Liquidate( uint256 _tokenId, IERC721 _nftToken, IERC20 _erc20Token, uint256 _lenderNftTokenId, uint256 _bTokenId ); constructor(BorrowToken _bToken, LenderToken _lToken) { bToken = _bToken; lToken = _lToken; } modifier isPause() { require(!pause, "Now Pause"); _; } modifier checkDebt(uint256 _amount) { require(_amount > 0, "The amount must > 0"); _; } modifier checkWhiteList(IERC20 _address) { bool include; for (uint256 index = 0; index < whiteList.length; index++) { if (whiteList[index] == _address) { include = true; break; } } require(include, "The address is not whitelisted"); _; } modifier checkCollateralStatus( uint256 _nftTokenId, IERC721 _nftToken, uint256 _bTokenId, IERC20 _erc20Token ) { Nft memory _nft = _findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token); require(!_nft.marks.isRepay && _nft.marks.isBorrow, "NFT status wrong"); _; } function setPause(bool _pause) public onlyOwner { pause = _pause; } function setInterestRate(uint256 _interestRate) public isPause onlyOwner { interestRate = _interestRate; } function setCycle(uint256 _cycle) public isPause onlyOwner { cycle = _cycle; } function setEmergencyCycle(uint256 _emergencyCycle) public isPause onlyOwner { emergencyCycle = _emergencyCycle; } function setWhiteList(IERC20[] memory _whiteList) public isPause onlyOwner { whiteList = _whiteList; } function setFee(uint256 _fee) public isPause onlyOwner { fee = _fee; } function getWhiteListLength() public view returns (uint256 length) { length = whiteList.length; } function addWhiteList(IERC20 _address) public isPause onlyOwner { whiteList.push(_address); } function _addNftAdr(IERC721 _nftToken) internal { uint256 len = NftAdrList.length; bool hasAdr = false; for (uint256 index = 0; index < len; index++) { if (_nftToken == NftAdrList[index]) { hasAdr = true; break; } } if (!hasAdr) NftAdrList.push(_nftToken); } function getNftMapLength(IERC721 _nftToken) public view returns (uint256 length) { length = NftMap[_nftToken].length; } function getNftAdrListLength() public view returns (uint256 length) { length = NftAdrList.length; } function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data ) public override(ERC721Holder) returns (bytes4) { emit NFTReceived(operator, from, tokenId, data); return bytes4( keccak256("onERC721Received(address,address,uint256,bytes)") ); } // deposit NFT function depositErc721( uint256 _nftTokenId, IERC721 _nftToken, uint256 _amount, IERC20 _erc20Token ) public isPause checkDebt(_amount) checkWhiteList(_erc20Token) { bool isERC721 = IERC721(_nftToken).supportsInterface(0x80ac58cd); require(isERC721, "Parameter _nftToken is not ERC721 contract address"); // mint bToken uint256 _bTokenId = bToken.mint(msg.sender); _addNftAdr(_nftToken); MARK memory _mark = MARK(false, false, false); // save collateral info NftMap[_nftToken].push( Nft({ holder: msg.sender, tokenId: _nftTokenId, nftToken: _nftToken, amount: _amount, erc20Token: _erc20Token, bTokenId: _bTokenId, borrowBlock: 0, borrowTimestamp: 0, emergencyTimestamp: 0, repayAmount: 0, lTokenId: 0, marks: _mark }) ); IERC721(_nftToken).safeTransferFrom( msg.sender, address(this), _nftTokenId ); emit DepositErc721(_nftTokenId, _nftToken, _amount, _erc20Token); } // Lend ERC20 function lendERC20( uint256 _nftTokenId, IERC721 _nftToken, uint256 _amount, IERC20 _erc20Token, uint256 _bTokenId ) public isPause checkDebt(_amount) checkWhiteList(_erc20Token) { Nft memory _nft = _findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token); require(!_nft.marks.isBorrow, "This collateral already borrowed"); // mint lToken uint256 _lTokenId = lToken.mint(msg.sender); // set collateral lTokenid _setCollateralLTokenId(_nftTokenId, _nftToken, _bTokenId, _lTokenId); // get lend amount uint256 tempAmount = calcLenderAmount(_nftTokenId, _nftToken, _bTokenId, _erc20Token); require(_amount >= tempAmount, "The _amount is not match"); // get fee uint256 _fee = _amount - _nft.amount; IERC20(_erc20Token).safeTransferFrom( address(msg.sender), address(this), _amount ); IERC20(_erc20Token).safeTransfer(owner(), _fee); emit LendERC20(_nftTokenId, _nftToken, _amount, _erc20Token, _bTokenId); // borrow action _borrow(_nftTokenId, _nftToken, _erc20Token, _bTokenId); } function _borrow( uint256 _nftTokenId, IERC721 _nftToken, IERC20 _erc20Token, uint256 _bTokenId ) internal { Nft memory _nft = _findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token); // change collateral status _changeCollateralStatus( _nftTokenId, _nftToken, true, false, false, block.timestamp, _nft.repayAmount, _nft.emergencyTimestamp ); // send erc20 token to collateral _nft.holder IERC20(_erc20Token).safeTransfer(address(_nft.holder), _nft.amount); emit Borrow( _nftTokenId, _nftToken, _nft.amount, _erc20Token, _bTokenId ); } function repay( uint256 _nftTokenId, IERC721 _nftToken, uint256 _amount, IERC20 _erc20Token, uint256 _bTokenId ) public isPause checkDebt(_amount) checkWhiteList(_erc20Token) { Nft memory _nft = _findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token); // get repay amount uint256 _repayAmount = calcInterestRate( _nftTokenId, _nftToken, _bTokenId, _erc20Token, true ); require(_amount >= _repayAmount, "Wrong amount."); // change collateral status _changeCollateralStatus( _nftTokenId, _nftToken, false, true, false, _nft.borrowTimestamp, _repayAmount, _nft.emergencyTimestamp ); // send erc20 token to contract IERC20(_erc20Token).safeTransferFrom( address(msg.sender), address(this), _repayAmount ); emit Repay( _nftTokenId, _nftToken, _repayAmount, _erc20Token, _bTokenId ); } function claimCollateral( uint256 _nftTokenId, IERC721 _nftToken, IERC20 _erc20Token, uint256 _bTokenId ) public isPause { Nft memory _nft = _findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token); if (_nft.marks.isBorrow) { require(_nft.marks.isRepay, "This debt is not repay"); } _changeCollateralStatus( _nftTokenId, _nftToken, false, true, true, _nft.borrowTimestamp, _nft.repayAmount, _nft.emergencyTimestamp ); // send bToken to contract for widthdraw collateral IERC721(bToken).safeTransferFrom(msg.sender, address(0), _bTokenId); // send collateral to msg.sender IERC721(_nftToken).safeTransferFrom( address(this), msg.sender, _nftTokenId ); emit ClaimCollateral(_nftTokenId, _nftToken, _erc20Token, _bTokenId); } function lTokenClaimERC20( uint256 _nftTokenId, IERC721 _nftToken, IERC20 _erc20Token, uint256 _lTokenId, uint256 _bTokenId ) public isPause checkWhiteList(_erc20Token) { // check collateral holder has borrow Nft memory _nft = _findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token); require(_nft.marks.isRepay, "This debt is not clear"); // send lToken to contract IERC721(lToken).safeTransferFrom(msg.sender, address(0), _lTokenId); // send erc20 token to msg.sender IERC20(_erc20Token).safeTransfer(msg.sender, _nft.repayAmount); emit LTokenClaimERC20( _nftTokenId, _nftToken, _nft.repayAmount, _erc20Token, _lTokenId, _bTokenId ); } function executeEmergency( uint256 _nftTokenId, IERC721 _nftToken, IERC20 _erc20Token, uint256 _lTokenId, uint256 _bTokenId ) public isPause checkCollateralStatus(_nftTokenId, _nftToken, _bTokenId, _erc20Token) { Nft memory _nft = _findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token); uint256 time = _nft.borrowTimestamp; // An emergency can be triggered after 30 days require( (block.timestamp - time) > cycle, "Can do not execute emergency." ); // set trigger emergency timestamp for withdraw collateral _changeCollateralStatus( _nftTokenId, _nftToken, _nft.marks.isBorrow, _nft.marks.isRepay, _nft.marks.hasWithdraw, _nft.borrowTimestamp, _nft.repayAmount, block.timestamp ); // send lToken for verify IERC721(lToken).safeTransferFrom(msg.sender, address(this), _lTokenId); IERC721(lToken).safeTransferFrom(address(this), msg.sender, _lTokenId); emit ExecuteEmergency( _nftTokenId, _nftToken, _erc20Token, _lTokenId, _bTokenId ); } function liquidate( uint256 _nftTokenId, IERC721 _nftToken, IERC20 _erc20Token, uint256 _lTokenId, uint256 _bTokenId ) public isPause checkCollateralStatus(_nftTokenId, _nftToken, _bTokenId, _erc20Token) { Nft memory _nft = _findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token); // send lToken for verify IERC721(lToken).safeTransferFrom(msg.sender, address(0), _lTokenId); uint256 _emerTime = _nft.emergencyTimestamp; // An emergency withdraw can be triggered after 15 days require( (block.timestamp - _emerTime) > emergencyCycle, "Can do not liquidate." ); // send collateral to lToken holder IERC721(_nftToken).safeTransferFrom( address(this), msg.sender, _nftTokenId ); _changeCollateralStatus( _nftTokenId, _nftToken, false, true, true, _nft.borrowTimestamp, _nft.repayAmount, _nft.emergencyTimestamp ); emit Liquidate( _nftTokenId, _nftToken, _erc20Token, _lTokenId, _bTokenId ); } function _changeCollateralStatus( uint256 _nftTokenId, IERC721 _nftToken, bool isBorrow, bool isRepay, bool hasWithdraw, uint256 _borrowTimestamp, uint256 _repayAmount, uint256 _emergencyTimestamp ) internal { Nft[] storage nftList = NftMap[_nftToken]; Nft storage nft; bool _hasNft = false; for (uint256 index = nftList.length - 1; index >= 0; index--) { nft = nftList[index]; if (nft.tokenId == _nftTokenId && _nftToken == nft.nftToken) { _hasNft = true; nft.marks.isBorrow = isBorrow; nft.marks.isRepay = isRepay; nft.marks.hasWithdraw = hasWithdraw; if (isBorrow) nft.borrowBlock = block.number; nft.borrowTimestamp = _borrowTimestamp; nft.repayAmount = _repayAmount; nft.emergencyTimestamp = _emergencyTimestamp; break; } } require(_hasNft, "Not find this nft -> changeCollateralStatus"); } function calcInterestRate( uint256 _nftTokenId, IERC721 _nftToken, uint256 _bTokenId, IERC20 _erc20Token, bool _isRepay ) public view returns (uint256 repayAmount) { uint256 _borrowBlock; uint256 base = _isRepay ? 100 : 101; Nft memory _nft = _findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token); // repayAmount = _nft.amount; _borrowBlock = block.number - _nft.borrowBlock; uint256 _interestRate = (_borrowBlock * interestRate * _nft.amount) / 10**18; // repayAmount = _interestRate + (_nft.amount / 100) * base; repayAmount = _interestRate.add(_nft.amount.mul(base).div(100)); } function calcLenderAmount( uint256 _nftTokenId, IERC721 _nftToken, uint256 _bTokenId, IERC20 _erc20Token ) public view returns (uint256 tempAmount) { Nft memory _nft = _findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token); tempAmount = _nft.amount.mul(10000 + fee).div(10000); // tempAmount = (_nft.amount / 10000) * (10000 + fee); } function _setCollateralLTokenId( uint256 _nftTokenId, IERC721 _nftToken, uint256 _bTokenId, uint256 _lTokenId ) internal { Nft[] storage nftList = NftMap[_nftToken]; Nft storage nft; bool _hasNft = false; for (uint256 index = nftList.length - 1; index >= 0; index--) { nft = nftList[index]; if ( nft.tokenId == _nftTokenId && _nftToken == nft.nftToken && nft.bTokenId == _bTokenId ) { _hasNft = true; nft.lTokenId = _lTokenId; break; } } require(_hasNft, "Not find this nft -> _setCollateralLTokenId"); } function _findNft( uint256 _nftTokenId, IERC721 _nftToken, uint256 _bTokenId, IERC20 _erc20Token ) internal view returns (Nft memory) { bool _hasNft = false; Nft[] memory nftList = NftMap[_nftToken]; Nft memory _nft; for (uint256 index = nftList.length - 1; index >= 0; index--) { _nft = nftList[index]; if ( _nft.tokenId == _nftTokenId && _nft.nftToken == _nftToken && _nft.bTokenId == _bTokenId && _nft.erc20Token == _erc20Token ) { _hasNft = true; break; } } require(_hasNft, "Not find this nft -> _findNft"); return _nft; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract LenderToken is ERC721URIStorage, ERC721Enumerable, Ownable, ERC721Burnable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; string public prefix = "http://app.kyoko.finance/ltoken/"; string public suffix = ".png"; constructor() ERC721("KyokoLToken", "KL") {} function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, amount); } function mint(address player) public onlyOwner returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); string memory _index = uint2str(newItemId); string memory _URI = strConcat(prefix, _index, suffix); _mint(player, newItemId); _setTokenURI(newItemId, _URI); return newItemId; } function burn(uint256 tokenId) public virtual override(ERC721Burnable) { super._burn(tokenId); } function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function uint2str(uint256 _i) public pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } function strConcat( string memory _a, string memory _b, string memory _c ) public pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); string memory ret = new string(_ba.length + _bb.length + _bc.length); bytes memory bret = bytes(ret); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i++) bret[k++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i++) bret[k++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i++) bret[k++] = _bc[i]; return string(ret); } } // 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 Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "./extensions/IERC721Enumerable.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}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../utils/Context.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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 pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @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; } } // 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; // 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.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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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;` */ 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
emergency timestamp
uint256 emergencyTimestamp;
1,710,492
[ 1, 351, 24530, 2858, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 801, 24530, 4921, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xC0A604e1dc71B5FBf3f396fC7a765605471aD710/sources/SampleToken.sol
Check if spender is not blacklisted
require(!isblacklistedAccount[spender]);
16,998,133
[ 1, 1564, 309, 17571, 264, 353, 486, 25350, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 5, 291, 11223, 18647, 3032, 63, 87, 1302, 264, 19226, 5375, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0xb02B34c48138464888A477a6F0CC96d8Ce2Fe3F0/sources/contracts/InheritanceUnitTest.sol
@dev return result and call error bool flag
function callSalary(ISalaried _submission) internal returns (uint, bool) { try _submission.annualSalary() returns (uint result) { return (result, false); return (0, true); } }
11,511,044
[ 1, 2463, 563, 471, 745, 555, 1426, 2982, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 745, 55, 287, 814, 12, 5127, 287, 297, 2092, 389, 12684, 13, 2713, 1135, 261, 11890, 16, 1426, 13, 288, 203, 3639, 775, 389, 12684, 18, 1072, 1462, 55, 287, 814, 1435, 1135, 261, 11890, 563, 13, 288, 203, 5411, 327, 261, 2088, 16, 629, 1769, 203, 5411, 327, 261, 20, 16, 638, 1769, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xb34879740cDC29eAF62215eEBf5214fCBb0EE235/sources/main.sol
Take ownership from the current owner. @param newIpfsImgHash: New hash to set the image to. Someone cannot transfer ownership to themselves. Transfer eth from sender to contract. Transfer eth from contract to previous owner. Finalize transfer of ownership to new owner.
function buy(string memory newIpfsImgHash) payable public { require(msg.sender != owner, "Owner cannot purchase from themselves."); require(msg.value == cost, "Insufficient funds provided. Must pay current cost."); require(success, "Transfer of funds to previous owner failed."); owner = msg.sender; ipfsImgHash = newIpfsImgHash; cost *= 2; }
789,314
[ 1, 13391, 23178, 628, 326, 783, 3410, 18, 225, 394, 5273, 2556, 12804, 2310, 30, 1166, 1651, 358, 444, 326, 1316, 358, 18, 10548, 476, 2780, 7412, 23178, 358, 20968, 18, 12279, 13750, 628, 5793, 358, 6835, 18, 12279, 13750, 628, 6835, 358, 2416, 3410, 18, 30740, 7412, 434, 23178, 358, 394, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 12, 1080, 3778, 394, 5273, 2556, 12804, 2310, 13, 8843, 429, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 480, 3410, 16, 315, 5541, 2780, 23701, 628, 20968, 1199, 1769, 203, 377, 202, 203, 377, 202, 6528, 12, 3576, 18, 1132, 422, 6991, 16, 315, 5048, 11339, 284, 19156, 2112, 18, 6753, 8843, 783, 6991, 1199, 1769, 203, 377, 203, 377, 202, 6528, 12, 4768, 16, 315, 5912, 434, 284, 19156, 358, 2416, 3410, 2535, 1199, 1769, 203, 377, 203, 377, 202, 8443, 273, 1234, 18, 15330, 31, 203, 377, 202, 625, 2556, 12804, 2310, 273, 394, 5273, 2556, 12804, 2310, 31, 203, 377, 202, 12398, 6413, 576, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; interface ERC820ImplementerInterface { /// @notice Contracts that implement an interferce in behalf of another contract must return true /// @param addr Address that the contract woll implement the interface in behalf of /// @param interfaceHash keccak256 of the name of the interface /// @return ERC820_ACCEPT_MAGIC if the contract can implement the interface represented by /// `ìnterfaceHash` in behalf of `addr` function canImplementInterfaceForAddress(address addr, bytes32 interfaceHash) view public returns(bytes32); } contract ERC820Registry { bytes4 constant InvalidID = 0xffffffff; bytes4 constant ERC165ID = 0x01ffc9a7; bytes32 constant ERC820_ACCEPT_MAGIC = keccak256("ERC820_ACCEPT_MAGIC"); mapping (address => mapping(bytes32 => address)) interfaces; mapping (address => address) managers; mapping (address => mapping(bytes4 => bool)) erc165Cache; event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed addr, address indexed newManager); /// @notice Query the hash of an interface given a name /// @param interfaceName Name of the interfce function interfaceHash(string interfaceName) public pure returns(bytes32) { return keccak256(interfaceName); } /// @notice GetManager function getManager(address addr) public view returns(address) { // By default the manager of an address is the same address if (managers[addr] == 0) { return addr; } else { return managers[addr]; } } /// @notice Sets an external `manager` that will be able to call `setInterfaceImplementer()` /// on behalf of the address. /// @param _addr Address that you are defining the manager for. (0x0 if is msg.sender) /// @param newManager The address of the manager for the `addr` that will replace /// the old one. Set to 0x0 if you want to remove the manager. function setManager(address _addr, address newManager) public { address addr = _addr == 0 ? msg.sender : _addr; require(getManager(addr) == msg.sender); managers[addr] = newManager == addr ? 0 : newManager; ManagerChanged(addr, newManager); } /// @notice Query if an address implements an interface and thru which contract /// @param _addr Address that is being queried for the implementation of an interface /// (if _addr == 0 them `msg.sender` is assumed) /// @param iHash SHA3 of the name of the interface as a string /// Example `web3.utils.sha3('ERC777Token`')` /// @return The address of the contract that implements a specific interface /// or 0x0 if `addr` does not implement this interface function getInterfaceImplementer(address _addr, bytes32 iHash) constant public returns (address) { address addr = _addr == 0 ? msg.sender : _addr; if (isERC165Interface(iHash)) { bytes4 i165Hash = bytes4(iHash); return erc165InterfaceSupported(addr, i165Hash) ? addr : 0; } return interfaces[addr][iHash]; } /// @notice Sets the contract that will handle a specific interface; only /// a `manager` defined for that address can set it. /// ( Each address is the manager for itself until a new manager is defined) /// @param _addr Address that you want to define the interface for /// (if _addr == 0 them `msg.sender` is assumed) /// @param iHash SHA3 of the name of the interface as a string /// For example `web3.utils.sha3('Ierc777')` for the Ierc777 function setInterfaceImplementer(address _addr, bytes32 iHash, address implementer) public { address addr = _addr == 0 ? msg.sender : _addr; require(getManager(addr) == msg.sender); require(!isERC165Interface(iHash)); if ((implementer != 0) && (implementer!=msg.sender)) { require(ERC820ImplementerInterface(implementer).canImplementInterfaceForAddress(addr, iHash) == ERC820_ACCEPT_MAGIC); } interfaces[addr][iHash] = implementer; InterfaceImplementerSet(addr, iHash, implementer); } /// ERC165 Specific function isERC165Interface(bytes32 iHash) internal pure returns (bool) { return iHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0; } function erc165InterfaceSupported(address _contract, bytes4 _interfaceId) constant public returns (bool) { if (!erc165Cache[_contract][_interfaceId]) { erc165UpdateCache(_contract, _interfaceId); } return interfaces[_contract][_interfaceId] != 0; } function erc165UpdateCache(address _contract, bytes4 _interfaceId) public { interfaces[_contract][_interfaceId] = erc165InterfaceSupported_NoCache(_contract, _interfaceId) ? _contract : 0; erc165Cache[_contract][_interfaceId] = true; } function erc165InterfaceSupported_NoCache(address _contract, bytes4 _interfaceId) public constant returns (bool) { uint256 success; uint256 result; (success, result) = noThrowCall(_contract, ERC165ID); if ((success==0)||(result==0)) { return false; } (success, result) = noThrowCall(_contract, InvalidID); if ((success==0)||(result!=0)) { return false; } (success, result) = noThrowCall(_contract, _interfaceId); if ((success==1)&&(result==1)) { return true; } return false; } function noThrowCall(address _contract, bytes4 _interfaceId) constant internal returns (uint256 success, uint256 result) { bytes4 erc165ID = ERC165ID; assembly { let x := mload(0x40) // Find empty storage location using "free memory pointer" mstore(x, erc165ID) // Place signature at begining of empty storage mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature success := staticcall( 30000, // 30k gas _contract, // To addr x, // Inputs are stored at location x 0x08, // Inputs are 8 bytes long x, // Store output over input (saves space) 0x20) // Outputs are 32 bytes long result := mload(x) // Load the result } } }
@notice Query the hash of an interface given a name @param interfaceName Name of the interfce
function interfaceHash(string interfaceName) public pure returns(bytes32) { return keccak256(interfaceName); }
5,864,265
[ 1, 1138, 326, 1651, 434, 392, 1560, 864, 279, 508, 225, 24088, 1770, 434, 326, 1554, 74, 311, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1560, 2310, 12, 1080, 24088, 13, 1071, 16618, 1135, 12, 3890, 1578, 13, 288, 203, 3639, 327, 417, 24410, 581, 5034, 12, 5831, 461, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
contract A { function _preRelayedCall(bytes memory context) internal virtual override returns (bytes32) { (address from, uint256 maxPossibleCharge) = abi.decode(context, (address, uint256)); // The maximum token charge is pre-charged from the user _token.safeTransferFrom(from, address(this), maxPossibleCharge); } }
The maximum token charge is pre-charged from the user
function _preRelayedCall(bytes memory context) internal virtual override returns (bytes32) { (address from, uint256 maxPossibleCharge) = abi.decode(context, (address, uint256)); _token.safeTransferFrom(from, address(this), maxPossibleCharge); }
5,428,244
[ 1, 1986, 4207, 1147, 13765, 353, 675, 17, 3001, 2423, 628, 326, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1484, 27186, 329, 1477, 12, 3890, 3778, 819, 13, 2713, 5024, 3849, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 261, 2867, 628, 16, 2254, 5034, 943, 13576, 17649, 13, 273, 24126, 18, 3922, 12, 2472, 16, 261, 2867, 16, 2254, 5034, 10019, 203, 203, 3639, 389, 2316, 18, 4626, 5912, 1265, 12, 2080, 16, 1758, 12, 2211, 3631, 943, 13576, 17649, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../interfaces/IRiverBox.sol"; import "../interfaces/IRiverBoxRandom.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract RiverBoxImpl is IRiverBox, ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable, UUPSUpgradeable, OwnableUpgradeable { using StringsUpgradeable for uint256; using SafeMathUpgradeable for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; CountersUpgradeable.Counter private _tokenIds; uint16[] private _stockLocations; uint32[] private _stockSignatures; uint32 private _stockCounter; /* ================ GLOBAL CONFIGURATION ================ */ // price per box - Pawn uint256 public boxPrice; uint256 public totalClaimableAmount; string public baseURI; address public randomGeneratorAddress; mapping(uint256 => string) private _tokenURIs; mapping(uint256 => Product) private _tokenDetailsMapping; mapping(address => uint256) public paidBoxes; // number of boxes user has bought mapping(uint256 => Hierarchy) private _tokenHierarchyMapping; mapping(address => uint256) public claimableAmountMapping; mapping(address => uint256) public referrerContrib; uint256 public totalReferrerContrib; address proxyRegistryAddress; /* ================ SHARES ================ */ address public funderAddress; address public devAddress; address public marketAddress; uint8 public devShare; uint8 public marketShare; bool public fuseLock; function initialize( uint256 _boxPrice, string memory _name, string memory _symbol, string memory _initBaseURI, address _proxyRegistryAddress ) public initializer { __Ownable_init(); __Pausable_init(); __AccessControl_init(); __ReentrancyGuard_init(); __ERC721_init(_name, _symbol); __UUPSUpgradeable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _pause(); fuseLock = true; boxPrice = _boxPrice; baseURI = _initBaseURI; proxyRegistryAddress = _proxyRegistryAddress; } /* ================ UTIL FUNCTIONS ================ */ function _pickLocation(uint256 index) internal returns (uint16, uint32) { uint256 lastIndex = _stockLocations.length - 1; uint16 lastStockLocation = _stockLocations[lastIndex]; uint16 locationId = _stockLocations[index]; _stockLocations[index] = lastStockLocation; _stockLocations.pop(); uint32 lastSignature = _stockSignatures[lastIndex]; uint32 signature = _stockSignatures[index]; _stockSignatures[index] = lastSignature; _stockSignatures.pop(); return (locationId, signature); } /* ================ VIEWS ================ */ function pawnsStock() public view returns (uint256) { return _stockLocations.length.sub(totalClaimableAmount); } function batchStockInfo(uint256 startIndex, uint256 length) public view returns (uint256[] memory, uint256[] memory) { require(startIndex < _stockLocations.length, "startIndex cannot over stockLocationsLength"); require(length > 0, "length cannot equal 0"); uint256 endIndex = MathUpgradeable.min(startIndex + length, _stockLocations.length); uint256 realLength = endIndex - startIndex; uint256[] memory locationIds = new uint256[](realLength); uint256[] memory signatures = new uint256[](realLength); for (uint256 idx = 0; idx < realLength; ++idx) { locationIds[idx] = _stockLocations[startIndex.add(idx)]; signatures[idx] = _stockSignatures[startIndex.add(idx)]; } return (locationIds, signatures); } /** * @dev Ultimate view for inspecting a token * @param tokenId the unique ID of a RiverMenNFT token * @return [[locationId, fusionCount, signature, creationTime, parts], ownerAddress, tokenURI, dealId] * @notice dealId = 0 means the item is not listed in exchange */ function allInfo(uint256 tokenId) public view returns ( Product memory, address, string memory ) { require(_exists(tokenId), "Token not exists"); return (_tokenDetailsMapping[tokenId], ownerOf(tokenId), tokenURI(tokenId)); } /** * @dev Get token detail information */ function tokenHierarchy(uint256 locationId) public view override returns (Hierarchy memory) { return _tokenHierarchyMapping[locationId]; } /** * @dev Get token detail information */ function tokenDetail(uint256 tokenId) public view override returns (Product memory) { require(_exists(tokenId), "Token not exists"); return _tokenDetailsMapping[tokenId]; } /** * @dev Verify if a list of parts can be used to fuse new product */ function verifyFusion(uint256[] memory tokenIds) public view override returns (bool) { if (tokenIds.length == 0) return false; require(_exists(tokenIds[0]), "Token not exists"); uint16 parentLocationId = _tokenHierarchyMapping[_tokenDetailsMapping[tokenIds[0]].locationId].parentLocationId; if (parentLocationId == 0) return false; uint16[] memory childLocationIds = _tokenHierarchyMapping[parentLocationId].childLocationIds; if (childLocationIds.length != tokenIds.length) return false; for (uint256 i = 0; i < tokenIds.length; ++i) { uint256 tokenId = tokenIds[i]; require(_exists(tokenId), "Token not exists"); if (_tokenDetailsMapping[tokenId].fusionCount > 0) return false; if (_tokenHierarchyMapping[_tokenDetailsMapping[tokenId].locationId].parentLocationId != parentLocationId) return false; if (ownerOf(tokenId) != _msgSender()) return false; // check duplicate TODO: find a more effective way and without using hash for (uint256 j = i + 1; j < tokenIds.length; ++j) { if (tokenId == tokenIds[j]) return false; } } return true; } function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view override(IRiverBox, ERC721Upgradeable) returns (string memory) { require(_exists(tokenId), "URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); if (bytes(_tokenURI).length > 0) { return _tokenURI; } else { return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : ""; } } function implementationVersion() public pure override returns (string memory) { return "1.2.1"; } /* ================ PRIVATE FUNCTIONS ================ */ function _notContract() internal view { uint256 size; address addr = msg.sender; assembly { size := extcodesize(addr) } require(size == 0, "contract not allowed"); require(msg.sender == tx.origin, "proxy contract not allowed"); } /** * @dev Mint a new Item * @param receiver account address to receive the new item */ function _awardItem(address receiver) private returns (uint256) { _tokenIds.increment(); uint256 newId = _tokenIds.current(); _safeMint(receiver, newId); return newId; } function _baseURI() internal view override(ERC721Upgradeable) returns (string memory) { return baseURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function _authorizeUpgrade(address) internal view override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission to do upgrades"); } /* ================ TRANSACTIONS ================ */ /** * @dev Buy N (n<10) boxes, this function receive payment and * mint new product(s) to sender * @param quality number of boxes * @param referrer referrer account address */ function buy(uint256 quality, address referrer) external payable override whenNotPaused nonReentrant { _notContract(); require(quality <= pawnsStock(), "blind box sold out"); require(quality <= 20, "exceed maximum quality 20"); require(msg.value >= boxPrice.mul(quality), "payment is less than box price"); boxesAward(quality, _msgSender()); if (referrer != address(0)) { referrerContrib[referrer] = referrerContrib[referrer].add(quality); totalReferrerContrib = totalReferrerContrib.add(quality); } paidBoxes[_msgSender()] = paidBoxes[_msgSender()].add(quality); } function boxesAward(uint256 quality, address receiver) internal { uint256 salt = uint256(keccak256(abi.encodePacked(quality, receiver, totalSupply()))); uint256 seed = IRiverBoxRandom(randomGeneratorAddress).generateSignature(salt); for (uint256 i = 0; i < quality; ++i) { seed = seed.add(totalSupply()); uint256 randomIdx = uint256(keccak256(abi.encodePacked(seed))).mod(_stockLocations.length); (uint16 pawnLocationId, uint32 signature) = _pickLocation(randomIdx); Product memory newItem = Product(pawnLocationId, 0, signature, new uint256[](0)); uint256 newId = _awardItem(receiver); _tokenDetailsMapping[newId] = newItem; emit BoxAwarded(receiver, newId, block.timestamp); } } /** * @dev Fuse a list of items to a next level product */ function fuse(uint256[] memory tokenIds) external override whenNotPaused nonReentrant { _notContract(); require(!fuseLock, "fusing is locked"); require(verifyFusion(tokenIds), "not a valid list of tokens"); uint16 parentLocationId = _tokenHierarchyMapping[_tokenDetailsMapping[tokenIds[0]].locationId].parentLocationId; Product memory newItem = Product(parentLocationId, 0, 0, tokenIds); for (uint256 i = 0; i < tokenIds.length; ++i) { _tokenDetailsMapping[tokenIds[i]].fusionCount = _tokenDetailsMapping[tokenIds[i]].fusionCount + 1; } uint256 newId = _awardItem(_msgSender()); _tokenDetailsMapping[newId] = newItem; emit FusedItemAwarded(_msgSender(), newId, block.timestamp); } /* ================ ADMIN ACTIONS ================ */ /** * @dev Set a new base URI * param newBaseURI new baseURI address */ function setBaseURI(string memory newBaseURI) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); baseURI = newBaseURI; } /** * @dev Set Hierarchy information to a specific node with locationId in batch * param locationIds A batch of locationId * param parentLocationIds A batch of parentLocationIds * param listChildLocationIds A batch of childLocationIds */ function setHierarchy( uint16[] memory locationIds, uint16[] memory parentLocationIds, uint16[][] memory listChildLocationIds ) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); for (uint256 i = 0; i < locationIds.length; ++i) { _tokenHierarchyMapping[locationIds[i]] = Hierarchy(parentLocationIds[i], listChildLocationIds[i]); } } function batchSetPawnLocationStock(uint16[] memory locationIds, uint16[] memory locationIdStocks) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); for (uint16 locationIdx = 0; locationIdx < locationIds.length; ++locationIdx) { uint16 locationId = locationIds[locationIdx]; uint16 locationIdStock = locationIdStocks[locationIdx]; for (uint16 stockIdx = 0; stockIdx < locationIdStock; ++stockIdx) { _stockLocations.push(locationId); _stockCounter = _stockCounter + 1; require(_stockCounter >= 1, "SafeMath: addition overflow"); _stockSignatures.push(_stockCounter); } } } /** * @dev Triggers stopped state. */ function pause() external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); _pause(); } /** * @dev Returns to normal state. */ function unPause() external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); _unpause(); } /** * @dev Triggers stopped state. * @param newPrice new box price */ function setBoxPrice(uint256 newPrice) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); boxPrice = newPrice; emit BoxPriceChanged(boxPrice, newPrice); } function setFuseLock(bool lock) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); fuseLock = lock; } /** * @dev Set random generator contract address * @param newAddress new random generator address */ function setRandomGenerator(address newAddress) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); randomGeneratorAddress = newAddress; } function setTokenURI(uint256 tokenId, string memory _tokenURI) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(_exists(tokenId), "URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function setShare( address _funderAddress, address _devAddress, address _marketAddress, uint8 _devShare, uint8 _marketShare ) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); funderAddress = _funderAddress; devAddress = _devAddress; marketAddress = _marketAddress; devShare = _devShare; marketShare = _marketShare; } function withdraw(uint256 amount) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(address(this).balance >= amount, "amount exceeds balance"); uint256 devAmount = amount.mul(uint256(devShare)).div(100); uint256 marketAmount = amount.mul(uint256(marketShare)).div(100); payable(devAddress).transfer(devAmount); payable(marketAddress).transfer(marketAmount); payable(funderAddress).transfer(amount.sub(devAmount).sub(marketAmount)); } function batchAirDrop(address[] memory receivers, uint256[] memory qualities) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(receivers.length == qualities.length, "receivers length must equal qualities length"); for (uint256 i = 0; i < qualities.length; ++i) { require(qualities[i] <= pawnsStock(), "out of stock"); totalClaimableAmount = totalClaimableAmount.add(qualities[i]); claimableAmountMapping[receivers[i]] = claimableAmountMapping[receivers[i]].add(qualities[i]); } } function claim(uint256 amount) external override whenNotPaused nonReentrant { _notContract(); require(amount <= claimableAmountMapping[_msgSender()], "out of claimable balance"); boxesAward(amount, _msgSender()); claimableAmountMapping[_msgSender()] = claimableAmountMapping[_msgSender()].sub(amount); totalClaimableAmount = totalClaimableAmount.sub(amount); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { //Whitelist OpenSea proxy contract for easy trading. if (proxyRegistryAddress != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } return super.isApprovedForAll(owner, operator); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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` 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[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library 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) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @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: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library 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] = 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) { 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.8.0; /** * @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;` */ library CountersUpgradeable { 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify * continuation of the upgradability. * * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { 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.8.2; pragma abicoder v2; interface IRiverBox { struct Hierarchy { uint16 parentLocationId; uint16[] childLocationIds; } struct Product { uint16 locationId; uint16 fusionCount; // number of times used to fuse item uint32 signature; // properties uint256[] parts; // a list token ids which are used to fuse this item } /* ================ EVENTS ================ */ /** * @dev Emitted when box price is changed. * @param from old price * @param to new price */ event BoxPriceChanged(uint256 indexed from, uint256 indexed to); event BoxAwarded(address indexed payer, uint256 indexed tokenId, uint256 eventTime); event FusedItemAwarded(address indexed payer, uint256 indexed tokenId, uint256 eventTime); /* ================ UTIL FUNCTIONS ================ */ /* ================ VIEWS ================ */ function tokenHierarchy(uint256 locationId) external view returns (Hierarchy memory); function tokenDetail(uint256 tokenId) external view returns (Product memory); function verifyFusion(uint256[] memory tokenIds) external view returns (bool); function tokenURI(uint256 tokenId) external view returns (string memory); function implementationVersion() external view returns (string memory); /* ================ TRANSACTIONS ================ */ function buy(uint256 quality, address referrer) external payable; function fuse(uint256[] memory tokenIds) external; /* ================ ADMIN ACTIONS ================ */ function setBaseURI(string memory newBaseURI) external; function setFuseLock(bool lock) external; function setHierarchy( uint16[] memory locationIds, uint16[] memory parentTokenIds, uint16[][] memory listChildTokenIds ) external; function pause() external; function unPause() external; function setBoxPrice(uint256 newPrice) external; function setRandomGenerator(address newAddress) external; function setTokenURI(uint256 tokenId, string memory _tokenURI) external; function setShare( address _funderAddress, address _devAddress, address _marketAddress, uint8 _devShare, uint8 _marketShare ) external; function withdraw(uint256 amount) external; function claim(uint256 amount) external; function batchAirDrop(address[] memory receivers, uint256[] memory qualitys) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; pragma abicoder v2; interface IRiverBoxRandom { function generateSignature(uint256 salt) external view returns (uint256); function setCaller(address riverBox) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { 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.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature( "upgradeTo(address)", oldImplementation ) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /* * @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) private returns (bytes memory) { require(AddressUpgradeable.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, "Address: low-level delegate call failed"); } 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); } } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } }
price per box - Pawn
{ using StringsUpgradeable for uint256; using SafeMathUpgradeable for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; CountersUpgradeable.Counter private _tokenIds; uint16[] private _stockLocations; uint32[] private _stockSignatures; uint32 private _stockCounter; uint256 public boxPrice; uint256 public totalClaimableAmount; string public baseURI; address public randomGeneratorAddress; mapping(uint256 => string) private _tokenURIs; mapping(uint256 => Product) private _tokenDetailsMapping; mapping(uint256 => Hierarchy) private _tokenHierarchyMapping; mapping(address => uint256) public claimableAmountMapping; mapping(address => uint256) public referrerContrib; uint256 public totalReferrerContrib; address proxyRegistryAddress; address public funderAddress; address public devAddress; address public marketAddress; uint8 public devShare; uint8 public marketShare; bool public fuseLock; function initialize( uint256 _boxPrice, string memory _name, string memory _symbol, string memory _initBaseURI, address _proxyRegistryAddress ) public initializer { __Ownable_init(); __Pausable_init(); __AccessControl_init(); __ReentrancyGuard_init(); __ERC721_init(_name, _symbol); __UUPSUpgradeable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _pause(); fuseLock = true; boxPrice = _boxPrice; baseURI = _initBaseURI; proxyRegistryAddress = _proxyRegistryAddress; } function _pickLocation(uint256 index) internal returns (uint16, uint32) { uint256 lastIndex = _stockLocations.length - 1; uint16 lastStockLocation = _stockLocations[lastIndex]; uint16 locationId = _stockLocations[index]; _stockLocations[index] = lastStockLocation; _stockLocations.pop(); uint32 lastSignature = _stockSignatures[lastIndex]; uint32 signature = _stockSignatures[index]; _stockSignatures[index] = lastSignature; _stockSignatures.pop(); return (locationId, signature); } function pawnsStock() public view returns (uint256) { return _stockLocations.length.sub(totalClaimableAmount); } function batchStockInfo(uint256 startIndex, uint256 length) public view returns (uint256[] memory, uint256[] memory) { require(startIndex < _stockLocations.length, "startIndex cannot over stockLocationsLength"); require(length > 0, "length cannot equal 0"); uint256 endIndex = MathUpgradeable.min(startIndex + length, _stockLocations.length); uint256 realLength = endIndex - startIndex; uint256[] memory locationIds = new uint256[](realLength); uint256[] memory signatures = new uint256[](realLength); for (uint256 idx = 0; idx < realLength; ++idx) { locationIds[idx] = _stockLocations[startIndex.add(idx)]; signatures[idx] = _stockSignatures[startIndex.add(idx)]; } return (locationIds, signatures); } function batchStockInfo(uint256 startIndex, uint256 length) public view returns (uint256[] memory, uint256[] memory) { require(startIndex < _stockLocations.length, "startIndex cannot over stockLocationsLength"); require(length > 0, "length cannot equal 0"); uint256 endIndex = MathUpgradeable.min(startIndex + length, _stockLocations.length); uint256 realLength = endIndex - startIndex; uint256[] memory locationIds = new uint256[](realLength); uint256[] memory signatures = new uint256[](realLength); for (uint256 idx = 0; idx < realLength; ++idx) { locationIds[idx] = _stockLocations[startIndex.add(idx)]; signatures[idx] = _stockSignatures[startIndex.add(idx)]; } return (locationIds, signatures); } function allInfo(uint256 tokenId) public view returns ( Product memory, address, string memory ) { require(_exists(tokenId), "Token not exists"); return (_tokenDetailsMapping[tokenId], ownerOf(tokenId), tokenURI(tokenId)); } function tokenHierarchy(uint256 locationId) public view override returns (Hierarchy memory) { return _tokenHierarchyMapping[locationId]; } function tokenDetail(uint256 tokenId) public view override returns (Product memory) { require(_exists(tokenId), "Token not exists"); return _tokenDetailsMapping[tokenId]; } function verifyFusion(uint256[] memory tokenIds) public view override returns (bool) { if (tokenIds.length == 0) return false; require(_exists(tokenIds[0]), "Token not exists"); uint16 parentLocationId = _tokenHierarchyMapping[_tokenDetailsMapping[tokenIds[0]].locationId].parentLocationId; if (parentLocationId == 0) return false; uint16[] memory childLocationIds = _tokenHierarchyMapping[parentLocationId].childLocationIds; if (childLocationIds.length != tokenIds.length) return false; for (uint256 i = 0; i < tokenIds.length; ++i) { uint256 tokenId = tokenIds[i]; require(_exists(tokenId), "Token not exists"); if (_tokenDetailsMapping[tokenId].fusionCount > 0) return false; if (_tokenHierarchyMapping[_tokenDetailsMapping[tokenId].locationId].parentLocationId != parentLocationId) return false; if (ownerOf(tokenId) != _msgSender()) return false; for (uint256 j = i + 1; j < tokenIds.length; ++j) { if (tokenId == tokenIds[j]) return false; } } return true; } function verifyFusion(uint256[] memory tokenIds) public view override returns (bool) { if (tokenIds.length == 0) return false; require(_exists(tokenIds[0]), "Token not exists"); uint16 parentLocationId = _tokenHierarchyMapping[_tokenDetailsMapping[tokenIds[0]].locationId].parentLocationId; if (parentLocationId == 0) return false; uint16[] memory childLocationIds = _tokenHierarchyMapping[parentLocationId].childLocationIds; if (childLocationIds.length != tokenIds.length) return false; for (uint256 i = 0; i < tokenIds.length; ++i) { uint256 tokenId = tokenIds[i]; require(_exists(tokenId), "Token not exists"); if (_tokenDetailsMapping[tokenId].fusionCount > 0) return false; if (_tokenHierarchyMapping[_tokenDetailsMapping[tokenId].locationId].parentLocationId != parentLocationId) return false; if (ownerOf(tokenId) != _msgSender()) return false; for (uint256 j = i + 1; j < tokenIds.length; ++j) { if (tokenId == tokenIds[j]) return false; } } return true; } function verifyFusion(uint256[] memory tokenIds) public view override returns (bool) { if (tokenIds.length == 0) return false; require(_exists(tokenIds[0]), "Token not exists"); uint16 parentLocationId = _tokenHierarchyMapping[_tokenDetailsMapping[tokenIds[0]].locationId].parentLocationId; if (parentLocationId == 0) return false; uint16[] memory childLocationIds = _tokenHierarchyMapping[parentLocationId].childLocationIds; if (childLocationIds.length != tokenIds.length) return false; for (uint256 i = 0; i < tokenIds.length; ++i) { uint256 tokenId = tokenIds[i]; require(_exists(tokenId), "Token not exists"); if (_tokenDetailsMapping[tokenId].fusionCount > 0) return false; if (_tokenHierarchyMapping[_tokenDetailsMapping[tokenId].locationId].parentLocationId != parentLocationId) return false; if (ownerOf(tokenId) != _msgSender()) return false; for (uint256 j = i + 1; j < tokenIds.length; ++j) { if (tokenId == tokenIds[j]) return false; } } return true; } function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view override(IRiverBox, ERC721Upgradeable) returns (string memory) { require(_exists(tokenId), "URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); if (bytes(_tokenURI).length > 0) { return _tokenURI; return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : ""; } } function tokenURI(uint256 tokenId) public view override(IRiverBox, ERC721Upgradeable) returns (string memory) { require(_exists(tokenId), "URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); if (bytes(_tokenURI).length > 0) { return _tokenURI; return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : ""; } } } else { function implementationVersion() public pure override returns (string memory) { return "1.2.1"; } function _notContract() internal view { uint256 size; address addr = msg.sender; assembly { size := extcodesize(addr) } require(size == 0, "contract not allowed"); require(msg.sender == tx.origin, "proxy contract not allowed"); } function _notContract() internal view { uint256 size; address addr = msg.sender; assembly { size := extcodesize(addr) } require(size == 0, "contract not allowed"); require(msg.sender == tx.origin, "proxy contract not allowed"); } function _awardItem(address receiver) private returns (uint256) { _tokenIds.increment(); uint256 newId = _tokenIds.current(); _safeMint(receiver, newId); return newId; } function _baseURI() internal view override(ERC721Upgradeable) returns (string memory) { return baseURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function _authorizeUpgrade(address) internal view override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission to do upgrades"); } function buy(uint256 quality, address referrer) external payable override whenNotPaused nonReentrant { _notContract(); require(quality <= pawnsStock(), "blind box sold out"); require(quality <= 20, "exceed maximum quality 20"); require(msg.value >= boxPrice.mul(quality), "payment is less than box price"); boxesAward(quality, _msgSender()); if (referrer != address(0)) { referrerContrib[referrer] = referrerContrib[referrer].add(quality); totalReferrerContrib = totalReferrerContrib.add(quality); } paidBoxes[_msgSender()] = paidBoxes[_msgSender()].add(quality); } function buy(uint256 quality, address referrer) external payable override whenNotPaused nonReentrant { _notContract(); require(quality <= pawnsStock(), "blind box sold out"); require(quality <= 20, "exceed maximum quality 20"); require(msg.value >= boxPrice.mul(quality), "payment is less than box price"); boxesAward(quality, _msgSender()); if (referrer != address(0)) { referrerContrib[referrer] = referrerContrib[referrer].add(quality); totalReferrerContrib = totalReferrerContrib.add(quality); } paidBoxes[_msgSender()] = paidBoxes[_msgSender()].add(quality); } function boxesAward(uint256 quality, address receiver) internal { uint256 salt = uint256(keccak256(abi.encodePacked(quality, receiver, totalSupply()))); uint256 seed = IRiverBoxRandom(randomGeneratorAddress).generateSignature(salt); for (uint256 i = 0; i < quality; ++i) { seed = seed.add(totalSupply()); uint256 randomIdx = uint256(keccak256(abi.encodePacked(seed))).mod(_stockLocations.length); (uint16 pawnLocationId, uint32 signature) = _pickLocation(randomIdx); Product memory newItem = Product(pawnLocationId, 0, signature, new uint256[](0)); uint256 newId = _awardItem(receiver); _tokenDetailsMapping[newId] = newItem; emit BoxAwarded(receiver, newId, block.timestamp); } } function boxesAward(uint256 quality, address receiver) internal { uint256 salt = uint256(keccak256(abi.encodePacked(quality, receiver, totalSupply()))); uint256 seed = IRiverBoxRandom(randomGeneratorAddress).generateSignature(salt); for (uint256 i = 0; i < quality; ++i) { seed = seed.add(totalSupply()); uint256 randomIdx = uint256(keccak256(abi.encodePacked(seed))).mod(_stockLocations.length); (uint16 pawnLocationId, uint32 signature) = _pickLocation(randomIdx); Product memory newItem = Product(pawnLocationId, 0, signature, new uint256[](0)); uint256 newId = _awardItem(receiver); _tokenDetailsMapping[newId] = newItem; emit BoxAwarded(receiver, newId, block.timestamp); } } function fuse(uint256[] memory tokenIds) external override whenNotPaused nonReentrant { _notContract(); require(!fuseLock, "fusing is locked"); require(verifyFusion(tokenIds), "not a valid list of tokens"); uint16 parentLocationId = _tokenHierarchyMapping[_tokenDetailsMapping[tokenIds[0]].locationId].parentLocationId; Product memory newItem = Product(parentLocationId, 0, 0, tokenIds); for (uint256 i = 0; i < tokenIds.length; ++i) { _tokenDetailsMapping[tokenIds[i]].fusionCount = _tokenDetailsMapping[tokenIds[i]].fusionCount + 1; } uint256 newId = _awardItem(_msgSender()); _tokenDetailsMapping[newId] = newItem; emit FusedItemAwarded(_msgSender(), newId, block.timestamp); } function fuse(uint256[] memory tokenIds) external override whenNotPaused nonReentrant { _notContract(); require(!fuseLock, "fusing is locked"); require(verifyFusion(tokenIds), "not a valid list of tokens"); uint16 parentLocationId = _tokenHierarchyMapping[_tokenDetailsMapping[tokenIds[0]].locationId].parentLocationId; Product memory newItem = Product(parentLocationId, 0, 0, tokenIds); for (uint256 i = 0; i < tokenIds.length; ++i) { _tokenDetailsMapping[tokenIds[i]].fusionCount = _tokenDetailsMapping[tokenIds[i]].fusionCount + 1; } uint256 newId = _awardItem(_msgSender()); _tokenDetailsMapping[newId] = newItem; emit FusedItemAwarded(_msgSender(), newId, block.timestamp); } function setBaseURI(string memory newBaseURI) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); baseURI = newBaseURI; } function setHierarchy( uint16[] memory locationIds, uint16[] memory parentLocationIds, uint16[][] memory listChildLocationIds ) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); for (uint256 i = 0; i < locationIds.length; ++i) { _tokenHierarchyMapping[locationIds[i]] = Hierarchy(parentLocationIds[i], listChildLocationIds[i]); } } function setHierarchy( uint16[] memory locationIds, uint16[] memory parentLocationIds, uint16[][] memory listChildLocationIds ) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); for (uint256 i = 0; i < locationIds.length; ++i) { _tokenHierarchyMapping[locationIds[i]] = Hierarchy(parentLocationIds[i], listChildLocationIds[i]); } } function batchSetPawnLocationStock(uint16[] memory locationIds, uint16[] memory locationIdStocks) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); for (uint16 locationIdx = 0; locationIdx < locationIds.length; ++locationIdx) { uint16 locationId = locationIds[locationIdx]; uint16 locationIdStock = locationIdStocks[locationIdx]; for (uint16 stockIdx = 0; stockIdx < locationIdStock; ++stockIdx) { _stockLocations.push(locationId); _stockCounter = _stockCounter + 1; require(_stockCounter >= 1, "SafeMath: addition overflow"); _stockSignatures.push(_stockCounter); } } } function batchSetPawnLocationStock(uint16[] memory locationIds, uint16[] memory locationIdStocks) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); for (uint16 locationIdx = 0; locationIdx < locationIds.length; ++locationIdx) { uint16 locationId = locationIds[locationIdx]; uint16 locationIdStock = locationIdStocks[locationIdx]; for (uint16 stockIdx = 0; stockIdx < locationIdStock; ++stockIdx) { _stockLocations.push(locationId); _stockCounter = _stockCounter + 1; require(_stockCounter >= 1, "SafeMath: addition overflow"); _stockSignatures.push(_stockCounter); } } } function batchSetPawnLocationStock(uint16[] memory locationIds, uint16[] memory locationIdStocks) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); for (uint16 locationIdx = 0; locationIdx < locationIds.length; ++locationIdx) { uint16 locationId = locationIds[locationIdx]; uint16 locationIdStock = locationIdStocks[locationIdx]; for (uint16 stockIdx = 0; stockIdx < locationIdStock; ++stockIdx) { _stockLocations.push(locationId); _stockCounter = _stockCounter + 1; require(_stockCounter >= 1, "SafeMath: addition overflow"); _stockSignatures.push(_stockCounter); } } } function pause() external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); _pause(); } function unPause() external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); _unpause(); } function setBoxPrice(uint256 newPrice) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); boxPrice = newPrice; emit BoxPriceChanged(boxPrice, newPrice); } function setFuseLock(bool lock) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); fuseLock = lock; } function setRandomGenerator(address newAddress) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); randomGeneratorAddress = newAddress; } function setTokenURI(uint256 tokenId, string memory _tokenURI) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(_exists(tokenId), "URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function setShare( address _funderAddress, address _devAddress, address _marketAddress, uint8 _devShare, uint8 _marketShare ) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); funderAddress = _funderAddress; devAddress = _devAddress; marketAddress = _marketAddress; devShare = _devShare; marketShare = _marketShare; } function withdraw(uint256 amount) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(address(this).balance >= amount, "amount exceeds balance"); uint256 devAmount = amount.mul(uint256(devShare)).div(100); uint256 marketAmount = amount.mul(uint256(marketShare)).div(100); payable(devAddress).transfer(devAmount); payable(marketAddress).transfer(marketAmount); payable(funderAddress).transfer(amount.sub(devAmount).sub(marketAmount)); } function batchAirDrop(address[] memory receivers, uint256[] memory qualities) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(receivers.length == qualities.length, "receivers length must equal qualities length"); for (uint256 i = 0; i < qualities.length; ++i) { require(qualities[i] <= pawnsStock(), "out of stock"); totalClaimableAmount = totalClaimableAmount.add(qualities[i]); claimableAmountMapping[receivers[i]] = claimableAmountMapping[receivers[i]].add(qualities[i]); } } function batchAirDrop(address[] memory receivers, uint256[] memory qualities) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(receivers.length == qualities.length, "receivers length must equal qualities length"); for (uint256 i = 0; i < qualities.length; ++i) { require(qualities[i] <= pawnsStock(), "out of stock"); totalClaimableAmount = totalClaimableAmount.add(qualities[i]); claimableAmountMapping[receivers[i]] = claimableAmountMapping[receivers[i]].add(qualities[i]); } } function claim(uint256 amount) external override whenNotPaused nonReentrant { _notContract(); require(amount <= claimableAmountMapping[_msgSender()], "out of claimable balance"); boxesAward(amount, _msgSender()); claimableAmountMapping[_msgSender()] = claimableAmountMapping[_msgSender()].sub(amount); totalClaimableAmount = totalClaimableAmount.sub(amount); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { if (proxyRegistryAddress != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } return super.isApprovedForAll(owner, operator); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { if (proxyRegistryAddress != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } return super.isApprovedForAll(owner, operator); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { if (proxyRegistryAddress != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } return super.isApprovedForAll(owner, operator); } }
12,230,438
[ 1, 8694, 1534, 3919, 300, 453, 9533, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 565, 1450, 8139, 10784, 429, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 10784, 429, 364, 2254, 5034, 31, 203, 565, 1450, 9354, 87, 10784, 429, 364, 9354, 87, 10784, 429, 18, 4789, 31, 203, 565, 1450, 6057, 25121, 694, 10784, 429, 364, 6057, 25121, 694, 10784, 429, 18, 5487, 694, 31, 203, 203, 565, 9354, 87, 10784, 429, 18, 4789, 3238, 389, 2316, 2673, 31, 203, 203, 565, 2254, 2313, 8526, 3238, 389, 15381, 10985, 31, 203, 565, 2254, 1578, 8526, 3238, 389, 15381, 23918, 31, 203, 565, 2254, 1578, 3238, 389, 15381, 4789, 31, 203, 203, 203, 565, 2254, 5034, 1071, 3919, 5147, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 9762, 429, 6275, 31, 203, 203, 565, 533, 1071, 1026, 3098, 31, 203, 203, 565, 1758, 1071, 2744, 3908, 1887, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 3238, 389, 2316, 1099, 2520, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 8094, 13, 3238, 389, 2316, 3790, 3233, 31, 203, 203, 203, 565, 2874, 12, 11890, 5034, 516, 670, 6000, 13, 3238, 389, 2316, 12074, 3233, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 7516, 429, 6275, 3233, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 14502, 442, 665, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 1957, 11110, 442, 665, 31, 203, 203, 565, 1758, 2889, 4243, 1887, 31, 203, 203, 565, 1758, 1071, 284, 9341, 1887, 31, 203, 565, 1758, 1071, 4461, 1887, 31, 2 ]
./full_match/4/0x87a4F79a4F856736070795f888f94C71C39B1cE1/sources/contracts/BondDepository.sol
Stored in bond info
uint256 priceInUSD = bondPriceInUSD();
724,288
[ 1, 18005, 316, 8427, 1123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 6205, 382, 3378, 40, 273, 8427, 5147, 382, 3378, 40, 5621, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0; pragma experimental ABIEncoderV2; import "../Interface/IBerry.sol"; /** * @title UserContract * This contracts creates for easy integration to the Berry System * by allowing smart contracts to read data off Berry */ contract UsingBerry { IBerry private berry; /*Constructor*/ /** * @dev the constructor sets the storage address and owner * @param _berry is the BerryMaster address */ constructor(address payable _berry) { berry = IBerry(_berry); } /** * @dev Retreive value from oracle based on requestId/timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return uint value for requestId/timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) public view returns (uint256) { return berry.retrieveData(_requestId, _timestamp); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to looku p * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) public view returns (bool) { return berry.isInDispute(_requestId, _timestamp); } /** * @dev Counts the number of values that have been submited for the request * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) public view returns (uint256) { return berry.getNewValueCountbyRequestId(_requestId); } /** * @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) public view returns (uint256) { return berry.getTimestampbyRequestIDandIndex(_requestId, _index); } /** * @dev Allows the user to get the latest value for the requestId specified * @param _requestId is the requestId to look up the value for * @return ifRetrieve bool true if it is able to retreive a value, the value, and the value's timestamp * @return value the value retrieved * @return _timestampRetrieved the value's timestamp */ function getCurrentValue(uint256 _requestId) public view returns ( bool ifRetrieve, uint256 value, uint256 _timestampRetrieved ) { uint256 _count = berry.getNewValueCountbyRequestId(_requestId); uint256 _time = berry.getTimestampbyRequestIDandIndex(_requestId, _count - 1); uint256 _value = berry.retrieveData(_requestId, _time); if (_value > 0) return (true, _value, _time); return (false, 0, _time); } // slither-disable-next-line calls-loop function getIndexForDataBefore(uint256 _requestId, uint256 _timestamp) public view returns (bool found, uint256 index) { uint256 _count = berry.getNewValueCountbyRequestId(_requestId); if (_count > 0) { uint256 middle; uint256 start = 0; uint256 end = _count - 1; uint256 _time; //Checking Boundaries to short-circuit the algorithm _time = berry.getTimestampbyRequestIDandIndex(_requestId, start); if (_time >= _timestamp) return (false, 0); _time = berry.getTimestampbyRequestIDandIndex(_requestId, end); if (_time < _timestamp) return (true, end); //Since the value is within our boundaries, do a binary search while (true) { middle = (end - start) / 2 + 1 + start; _time = berry.getTimestampbyRequestIDandIndex( _requestId, middle ); if (_time < _timestamp) { //get imeadiate next value uint256 _nextTime = berry.getTimestampbyRequestIDandIndex( _requestId, middle + 1 ); if (_nextTime >= _timestamp) { //_time is correct return (true, middle); } else { //look from middle + 1(next value) to end start = middle + 1; } } else { uint256 _prevTime = berry.getTimestampbyRequestIDandIndex( _requestId, middle - 1 ); if (_prevTime < _timestamp) { // _prevtime is correct return (true, middle - 1); } else { //look from start to middle -1(prev value) end = middle - 1; } } //We couldn't found a value //if(middle - 1 == start || middle == _count) return (false, 0); } } return (false, 0); } /** * @dev Allows the user to get the first value for the requestId before the specified timestamp * @param _requestId is the requestId to look up the value for * @param _timestamp before which to search for first verified value * @return _ifRetrieve bool true if it is able to retreive a value, the value, and the value's timestamp * @return _value the value retrieved * @return _timestampRetrieved the value's timestamp */ function getDataBefore(uint256 _requestId, uint256 _timestamp) public view returns ( bool _ifRetrieve, uint256 _value, uint256 _timestampRetrieved ) { (bool _found, uint256 _index) = getIndexForDataBefore(_requestId, _timestamp); if (!_found) return (false, 0, 0); uint256 _time = berry.getTimestampbyRequestIDandIndex(_requestId, _index); _value = berry.retrieveData(_requestId, _time); //If value is diputed it'll return zero if (_value > 0) return (true, _value, _time); return (false, 0, 0); } /** * @return Returns the current reward amount. TODO remove once https://github.com/proxy-io/TellorCore/issues/109 is implemented and deployed. */ function currentReward() external view returns (uint256) { uint256 rewardAccumulated; if (berry.getUintVar(keccak256("height")) > 172800) { rewardAccumulated = 0; } else { rewardAccumulated = 61728395061728390000 / (berry.getUintVar(keccak256("height")) / 43200 + 1); } uint256 tip = berry.getUintVar(keccak256("currentTotalTips")); return (rewardAccumulated + tip) / 5; // each miner } struct value { uint256 timestamp; uint256 value; } /** * @param requestID is the ID for which the function returns the values for. * @param count is the number of last values to return. * @return Returns the last N values for a request ID. */ function getLastNewValues(uint256 requestID, uint256 count) external view returns (value[] memory) { uint256 totalCount = berry.getNewValueCountbyRequestId(requestID); if (count > totalCount) { count = totalCount; } value[] memory values = new value[](count); for (uint256 i = 0; i < count; i++) { uint256 ts = berry.getTimestampbyRequestIDandIndex( requestID, totalCount - i - 1 ); uint256 v = berry.retrieveData(requestID, ts); values[i] = value({timestamp: ts, value: v}); } return values; } /** * @return Returns the contract owner that can do things at will. */ function _deity() external view returns (address) { return berry.getAddressVars(keccak256("_deity")); } /** * @return Returns the contract owner address. */ function _owner() external view returns (address) { return berry.getAddressVars(keccak256("_owner")); } /** * @return Returns the contract pending owner. */ function pending_owner() external view returns (address) { return berry.getAddressVars(keccak256("pending_owner")); } /** * @return Returns the contract address that executes all proxy calls. */ function berryContract() external view returns (address) { return berry.getAddressVars(keccak256("berryContract")); } /** * @param requestID is the ID for which the function returns the total tips. * @return Returns the current tips for a give request ID. */ function totalTip(uint256 requestID) external view returns (uint256) { return berry.getRequestUintVars(requestID, keccak256("totalTip")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the last time when a value was submitted. */ function timeOfLastNewValue() external view returns (uint256) { return berry.getUintVar(keccak256("timeOfLastNewValue")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the total number of requests from user thorugh the addTip function. */ function requestCount() external view returns (uint256) { return berry.getUintVar(keccak256("requestCount")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the current block difficulty. * */ function difficulty() external view returns (uint256) { return berry.getUintVar(keccak256("difficulty")); } /** * @return Returns the getUintVar variable named after the function name. * This variable is used to calculate the block difficulty based on * the time diff since the last oracle block. */ function timeTarget() external view returns (uint256) { return berry.getUintVar(keccak256("timeTarget")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the highest api/timestamp PayoutPool. */ function currentTotalTips() external view returns (uint256) { return berry.getUintVar(keccak256("currentTotalTips")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the number of miners who have mined this value so far. */ function slotProgress() external view returns (uint256) { return berry.getUintVar(keccak256("slotProgress")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the cost to dispute a mined value. */ function disputeFee() external view returns (uint256) { return berry.getUintVar(keccak256("disputeFee")); } /** * @return Returns the getUintVar variable named after the function name. */ function disputeCount() external view returns (uint256) { return berry.getUintVar(keccak256("disputeCount")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks stake amount required to become a miner. */ function stakeAmount() external view returns (uint256) { return berry.getUintVar(keccak256("stakeAmount")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the number of parties currently staked. */ function stakerCount() external view returns (uint256) { return berry.getUintVar(keccak256("stakerCount")); } }
* @return Returns the getUintVar variable named after the function name. This variable is used to calculate the block difficulty based on the time diff since the last oracle block./
function timeTarget() external view returns (uint256) { return berry.getUintVar(keccak256("timeTarget")); }
13,124,237
[ 1, 2463, 2860, 326, 336, 5487, 1537, 2190, 4141, 1839, 326, 445, 508, 18, 1220, 2190, 353, 1399, 358, 4604, 326, 1203, 3122, 21934, 2511, 603, 326, 813, 3122, 3241, 326, 1142, 20865, 1203, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 813, 2326, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 324, 21938, 18, 588, 5487, 1537, 12, 79, 24410, 581, 5034, 2932, 957, 2326, 7923, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // Version: 0.1.0, 1/20/2021 pragma solidity >=0.6.2 <0.8.0; import "../interface/IERC20.sol"; import "../interface/IPToken.sol"; import "../interface/ILToken.sol"; import "../interface/IOracle.sol"; import "../interface/ILiquidatorQualifier.sol"; import "../interface/IMigratablePool.sol"; import "../interface/IPreMiningPool.sol"; import "../interface/IPerpetualPool.sol"; import "../utils/SafeERC20.sol"; import "../math/MixedSafeMathWithUnit.sol"; import "./MigratablePool.sol"; /** * @title Deri Protocol PerpetualPool Implementation */ contract PerpetualPool is IMigratablePool, IPerpetualPool, MigratablePool { using MixedSafeMathWithUnit for uint256; using MixedSafeMathWithUnit for int256; using SafeERC20 for IERC20; // Trading symbol string private _symbol; // Last price uint256 private _price; // Last price timestamp uint256 private _lastPriceTimestamp; // Last price block number uint256 private _lastPriceBlockNumber; // Base token contract, all settlements are done in base token IERC20 private _bToken; // Base token decimals uint256 private _bDecimals; // Position token contract IPToken private _pToken; // Liquidity provider token contract ILToken private _lToken; // For on-chain oracle, it is a contract and must have getPrice() method to fetch current price // For off-chain signed price oracle, it is an EOA // and its address is used to verify price signature IOracle private _oracle; // Is on-chain oracle, or off-chain oracle with signed price bool private _isContractOracle; // LiquidatorQualifier contract to check if an address can call liquidate function // If this address is 0, means no liquidator qualification check, anyone can call liquidate ILiquidatorQualifier private _liquidatorQualifier; // Contract multiplier uint256 private _multiplier; // Trading fee ratio uint256 private _feeRatio; // Minimum pool margin ratio uint256 private _minPoolMarginRatio; // Minimum initial margin ratio for trader uint256 private _minInitialMarginRatio; // Minimum maintenance margin ratio for trader uint256 private _minMaintenanceMarginRatio; // Minimum amount requirement when add liquidity uint256 private _minAddLiquidity; // Redemption fee ratio when removing liquidity uint256 private _redemptionFeeRatio; // Funding rate coefficient uint256 private _fundingRateCoefficient; // Minimum liquidation reward uint256 private _minLiquidationReward; // Maximum liquidation reward uint256 private _maxLiquidationReward; // Cutting ratio for liquidator uint256 private _liquidationCutRatio; // Price delay allowance in seconds uint256 private _priceDelayAllowance; // Recorded cumulative funding rate, overflow of this value is intended int256 private _cumuFundingRate; // Last block number when cumulative funding rate was recorded uint256 private _cumuFundingRateBlock; // Total liquidity pool holds uint256 private _liquidity; // Total net volume of all traders in the pool int256 private _tradersNetVolume; // Total cost of current traders net volume // The cost for a long position is positive, and short position is negative int256 private _tradersNetCost; bool private _mutex; // Locker to prevent reentry modifier _lock_() { require(!_mutex, "PerpetualPool: reentry"); _mutex = true; _; _mutex = false; } /** * @dev A dummy constructor, which deos not initialize any storage variables * A template will be deployed with no initialization and real pool will be cloned * from this template (same as create_forwarder_to mechanism in Vyper), * and use `initialize` to initialize all storage variables */ constructor () {} /** * @dev See {IPerpetualPool}.{initialize} */ function initialize( string memory symbol_, address[5] calldata addresses_, uint256[12] calldata parameters_ ) public override { require(bytes(_symbol).length == 0 && _controller == address(0), "PerpetualPool: already initialized"); _controller = msg.sender; _symbol = symbol_; _bToken = IERC20(addresses_[0]); _bDecimals = _bToken.decimals(); _pToken = IPToken(addresses_[1]); _lToken = ILToken(addresses_[2]); _oracle = IOracle(addresses_[3]); _isContractOracle = _isContract(address(_oracle)); _liquidatorQualifier = ILiquidatorQualifier(addresses_[4]); _multiplier = parameters_[0]; _feeRatio = parameters_[1]; _minPoolMarginRatio = parameters_[2]; _minInitialMarginRatio = parameters_[3]; _minMaintenanceMarginRatio = parameters_[4]; _minAddLiquidity = parameters_[5]; _redemptionFeeRatio = parameters_[6]; _fundingRateCoefficient = parameters_[7]; _minLiquidationReward = parameters_[8]; _maxLiquidationReward = parameters_[9]; _liquidationCutRatio = parameters_[10]; _priceDelayAllowance = parameters_[11]; } /** * @dev See {IMigratablePool}.{approveMigration} */ function approveMigration() public override _controller_ { require(_migrationTimestamp != 0 && block.timestamp >= _migrationTimestamp, "PerpetualPool: migrationTimestamp not met yet"); // approve new pool to pull all base tokens from this pool _bToken.safeApprove(_migrationDestination, uint256(-1)); // set pToken/lToken to new pool, after redirecting pToken/lToken to new pool, this pool will stop functioning _pToken.setPool(_migrationDestination); _lToken.setPool(_migrationDestination); } /** * @dev See {IMigratablePool}.{executeMigration} */ function executeMigration(address source) public override _controller_ { uint256 migrationTimestamp_ = IPerpetualPool(source).migrationTimestamp(); address migrationDestination_ = IPerpetualPool(source).migrationDestination(); require(migrationTimestamp_ != 0 && block.timestamp >= migrationTimestamp_, "PerpetualPool: migrationTimestamp not met yet"); require(migrationDestination_ == address(this), "PerpetualPool: executeMigration to not destination pool"); // migrate base token _bToken.safeTransferFrom(source, address(this), _bToken.balanceOf(source)); // // migrate state values from PerpetualPool // (int256 cumuFundingRate, uint256 cumuFundingRateBlock, uint256 liquidity, int256 tradersNetVolume, int256 tradersNetCost) = IPerpetualPool(source).getStateValues(); // _cumuFundingRate = cumuFundingRate; // _cumuFundingRateBlock = cumuFundingRateBlock; // _liquidity = liquidity; // _tradersNetVolume = tradersNetVolume; // _tradersNetCost = tradersNetCost; // migrate state values from PreMiningPool _liquidity = IPreMiningPool(source).getStateValues(); emit ExecuteMigration(_migrationTimestamp, source, address(this)); } /** * @dev See {IPerpetualPool}.{symbol} */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IPerpetualPool}.{getAddresses} */ function getAddresses() public view override returns ( address bToken, address pToken, address lToken, address oracle, address liquidatorQualifier ) { return ( address(_bToken), address(_pToken), address(_lToken), address(_oracle), address(_liquidatorQualifier) ); } /** * @dev See {IPerpetualPool}.{getParameters} */ function getParameters() public view override returns ( uint256 multiplier, uint256 feeRatio, uint256 minPoolMarginRatio, uint256 minInitialMarginRatio, uint256 minMaintenanceMarginRatio, uint256 minAddLiquidity, uint256 redemptionFeeRatio, uint256 fundingRateCoefficient, uint256 minLiquidationReward, uint256 maxLiquidationReward, uint256 liquidationCutRatio, uint256 priceDelayAllowance ) { return ( _multiplier, _feeRatio, _minPoolMarginRatio, _minInitialMarginRatio, _minMaintenanceMarginRatio, _minAddLiquidity, _redemptionFeeRatio, _fundingRateCoefficient, _minLiquidationReward, _maxLiquidationReward, _liquidationCutRatio, _priceDelayAllowance ); } /** * @dev See {IPerpetualPool}.{getStateValues} */ function getStateValues() public view override returns ( int256 cumuFundingRate, uint256 cumuFundingRateBlock, uint256 liquidity, int256 tradersNetVolume, int256 tradersNetCost ) { return ( _cumuFundingRate, _cumuFundingRateBlock, _liquidity, _tradersNetVolume, _tradersNetCost ); } //================================================================================ // Pool interactions //================================================================================ /** * @dev See {IPerpetualPool}.{tradeWithMargin} */ function tradeWithMargin(int256 tradeVolume, uint256 bAmount) public override { _updatePriceFromOracle(); _tradeWithMargin(tradeVolume, bAmount); } /** * @dev See {IPerpetualPool}.{tradeWithMargin} */ function tradeWithMargin( int256 tradeVolume, uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { _updatePriceWithSignature(timestamp, price, v, r, s); _tradeWithMargin(tradeVolume, bAmount); } /** * @dev See {IPerpetualPool}.{trade} */ function trade(int256 tradeVolume) public override { _updatePriceFromOracle(); _trade(tradeVolume); } /** * @dev See {IPerpetualPool}.{trade} */ function trade( int256 tradeVolume, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { _updatePriceWithSignature(timestamp, price, v, r, s); _trade(tradeVolume); } /** * @dev See {IPerpetualPool}.{depositMargin} */ function depositMargin(uint256 bAmount) public override { _updatePriceFromOracle(); _depositMargin(bAmount); } /** * @dev See {IPerpetualPool}.{depositMargin} */ function depositMargin( uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { _updatePriceWithSignature(timestamp, price, v, r, s); _depositMargin(bAmount); } /** * @dev See {IPerpetualPool}.{withdrawMargin} */ function withdrawMargin(uint256 bAmount) public override { _updatePriceFromOracle(); _withdrawMargin(bAmount); } /** * @dev See {IPerpetualPool}.{withdrawMargin} */ function withdrawMargin( uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { _updatePriceWithSignature(timestamp, price, v, r, s); _withdrawMargin(bAmount); } /** * @dev See {IPerpetualPool}.{addLiquidity} */ function addLiquidity(uint256 bAmount) public override { _updatePriceFromOracle(); _addLiquidity(bAmount); } /** * @dev See {IPerpetualPool}.{addLiquidity} */ function addLiquidity( uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { _updatePriceWithSignature(timestamp, price, v, r, s); _addLiquidity(bAmount); } /** * @dev See {IPerpetualPool}.{removeLiquidity} */ function removeLiquidity(uint256 lShares) public override { _updatePriceFromOracle(); _removeLiquidity(lShares); } /** * @dev See {IPerpetualPool}.{removeLiquidity} */ function removeLiquidity( uint256 lShares, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { _updatePriceWithSignature(timestamp, price, v, r, s); _removeLiquidity(lShares); } /** * @dev See {IPerpetualPool}.{liquidate} */ function liquidate(address owner) public override { require( address(_liquidatorQualifier) == address(0) || _liquidatorQualifier.isQualifiedLiquidator(msg.sender), "PerpetualPool: not quanlified liquidator" ); _updatePriceFromOracle(); _liquidate(owner, block.timestamp, _price); } /** * @dev See {IPerpetualPool}.{liquidate} * * A price signature with timestamp after position's lastUpdateTimestamp * will be a valid liquidation price */ function liquidate( address owner, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) public override { require( address(_liquidatorQualifier) == address(0) || _liquidatorQualifier.isQualifiedLiquidator(msg.sender), "PerpetualPool: not quanlified liquidator" ); _checkPriceSignature(timestamp, price, v, r, s); _liquidate(owner, timestamp, price); } //================================================================================ // Pool critic logics //================================================================================ /** * @dev Low level tradeWithMargin implementation * _lock_ is not need in this function, as sub-functions will apply _lock_ */ function _tradeWithMargin(int256 tradeVolume, uint256 bAmount) internal { if (bAmount == 0) { _trade(tradeVolume); } else if (tradeVolume == 0) { _depositMargin(bAmount); } else { _depositMargin(bAmount); _trade(tradeVolume); } } /** * @dev Low level trade implementation */ function _trade(int256 tradeVolume) internal _lock_ { require(tradeVolume != 0, "PerpetualPool: trade with 0 volume"); require(tradeVolume.reformat(0) == tradeVolume, "PerpetualPool: trade volume must be int"); // get trader's position, trader must have a position token to call this function (int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin,) = _pToken.getPosition(msg.sender); // update cumulative funding rate _updateCumuFundingRate(_price); // calculate trader's funding fee int256 funding = volume.mul(_cumuFundingRate - lastCumuFundingRate); // calculate trading fee for this transaction int256 curCost = tradeVolume.mul(_price).mul(_multiplier); uint256 fee = _feeRatio.mul(curCost.abs()); // calculate realized cost int256 realizedCost = 0; if ((volume >= 0 && tradeVolume >= 0) || (volume <= 0 && tradeVolume <= 0)) { // open in same direction, no realized cost } else if (volume.abs() <= tradeVolume.abs()) { // previous position is flipped realizedCost = curCost.mul(volume.abs()).div(tradeVolume.abs()).add(cost); } else { // previous position is partially closed realizedCost = cost.mul(tradeVolume.abs()).div(volume.abs()).add(curCost); } // total paid in this transaction, could be negative if there is realized pnl // this paid amount should be a valid value in base token decimals representation int256 paid = funding.add(fee).add(realizedCost).reformat(_bDecimals); // settlements volume = volume.add(tradeVolume); cost = cost.add(curCost).sub(realizedCost); margin = margin.sub(paid); _tradersNetVolume = _tradersNetVolume.add(tradeVolume); _tradersNetCost = _tradersNetCost.add(curCost).sub(realizedCost); _liquidity = _liquidity.add(paid); lastCumuFundingRate = _cumuFundingRate; // check margin requirements require(volume == 0 || _calculateMarginRatio(volume, cost, _price, margin) >= _minInitialMarginRatio, "PerpetualPool: trader insufficient margin"); require(_tradersNetVolume == 0 || _calculateMarginRatio(_tradersNetVolume.neg(), _tradersNetCost.neg(), _price, _liquidity) >= _minPoolMarginRatio, "PerpetualPool: pool insufficient liquidity"); _pToken.update(msg.sender, volume, cost, lastCumuFundingRate, margin, block.timestamp); emit Trade(msg.sender, tradeVolume, _price); } /** * @dev Low level depositMargin implementation */ function _depositMargin(uint256 bAmount) internal _lock_ { require(bAmount != 0, "PerpetualPool: deposit zero margin"); require(bAmount.reformat(_bDecimals) == bAmount, "PerpetualPool: _depositMargin bAmount not valid"); bAmount = _deflationCompatibleSafeTransferFrom(msg.sender, address(this), bAmount); if (!_pToken.exists(msg.sender)) { _pToken.mint(msg.sender, bAmount); } else { (int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin,) = _pToken.getPosition(msg.sender); margin = margin.add(bAmount); _pToken.update(msg.sender, volume, cost, lastCumuFundingRate, margin, block.timestamp); } emit DepositMargin(msg.sender, bAmount); } /** * @dev Low level withdrawMargin implementation */ function _withdrawMargin(uint256 bAmount) internal _lock_ { require(bAmount != 0, "PerpetualPool: withdraw zero margin"); require(bAmount.reformat(_bDecimals) == bAmount, "PerpetualPool: _withdrawMargin bAmount not valid"); (int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin,) = _pToken.getPosition(msg.sender); _updateCumuFundingRate(_price); int256 funding = volume.mul(_cumuFundingRate - lastCumuFundingRate).reformat(_bDecimals); margin = margin.sub(funding).sub(bAmount); _liquidity = _liquidity.add(funding); lastCumuFundingRate = _cumuFundingRate; require(volume == 0 || _calculateMarginRatio(volume, cost, _price, margin) >= _minInitialMarginRatio, "PerpetualPool: withdraw cause insufficient margin"); _pToken.update(msg.sender, volume, cost, lastCumuFundingRate, margin, block.timestamp); _bToken.safeTransfer(msg.sender, bAmount.rescale(_bDecimals)); emit WithdrawMargin(msg.sender, bAmount); } /** * @dev Low level addLiquidity implementation */ function _addLiquidity(uint256 bAmount) internal _lock_ { require(bAmount >= _minAddLiquidity, "PerpetualPool: add liquidity less than minimum requirement"); require(bAmount.reformat(_bDecimals) == bAmount, "PerpetualPool: _addLiquidity bAmount not valid"); _updateCumuFundingRate(_price); bAmount = _deflationCompatibleSafeTransferFrom(msg.sender, address(this), bAmount); uint256 poolDynamicEquity = _liquidity.add(_tradersNetCost.sub(_tradersNetVolume.mul(_price).mul(_multiplier))); uint256 totalSupply = _lToken.totalSupply(); uint256 lShares; if (totalSupply == 0) { lShares = bAmount; } else { lShares = bAmount.mul(totalSupply).div(poolDynamicEquity); } _lToken.mint(msg.sender, lShares); _liquidity = _liquidity.add(bAmount); emit AddLiquidity(msg.sender, lShares, bAmount); } /** * @dev Low level removeLiquidity implementation */ function _removeLiquidity(uint256 lShares) internal _lock_ { require(lShares > 0, "PerpetualPool: remove 0 liquidity"); uint256 balance = _lToken.balanceOf(msg.sender); require(lShares == balance || balance.sub(lShares) >= 10**18, "PerpetualPool: remaining liquidity shares must be 0 or at least 1"); _updateCumuFundingRate(_price); uint256 poolDynamicEquity = _liquidity.add(_tradersNetCost.sub(_tradersNetVolume.mul(_price).mul(_multiplier))); uint256 totalSupply = _lToken.totalSupply(); uint256 bAmount = lShares.mul(poolDynamicEquity).div(totalSupply); if (lShares < totalSupply) { bAmount = bAmount.sub(bAmount.mul(_redemptionFeeRatio)); } bAmount = bAmount.reformat(_bDecimals); _liquidity = _liquidity.sub(bAmount); require(_tradersNetVolume == 0 || _calculateMarginRatio(_tradersNetVolume.neg(), _tradersNetCost.neg(), _price, _liquidity) >= _minPoolMarginRatio, "PerpetualPool: remove liquidity cause pool insufficient liquidity"); _lToken.burn(msg.sender, lShares); _bToken.safeTransfer(msg.sender, bAmount.rescale(_bDecimals)); emit RemoveLiquidity(msg.sender, lShares, bAmount); } /** * @dev Low level liquidate implementation */ function _liquidate(address owner, uint256 timestamp, uint256 price) internal _lock_ { (int256 volume, int256 cost, , uint256 margin, uint256 lastUpdateTimestamp) = _pToken.getPosition(owner); require(timestamp > lastUpdateTimestamp, "PerpetualPool: liquidate price is before position timestamp"); int256 pnl = volume.mul(price).mul(_multiplier).sub(cost); require(pnl.add(margin) <= 0 || _calculateMarginRatio(volume, cost, price, margin) < _minMaintenanceMarginRatio, "PerpetualPool: cannot liquidate"); _liquidity = _liquidity.add(margin); _tradersNetVolume = _tradersNetVolume.sub(volume); _tradersNetCost = _tradersNetCost.sub(cost); _pToken.update(owner, 0, 0, 0, 0, 0); uint256 reward; if (margin <= _minLiquidationReward) { reward = _minLiquidationReward; } else if (margin >= _maxLiquidationReward) { reward = _maxLiquidationReward; } else { reward = margin.sub(_minLiquidationReward).mul(_liquidationCutRatio).add(_minLiquidationReward); } reward = reward.reformat(_bDecimals); _liquidity = _liquidity.sub(reward); _bToken.safeTransfer(msg.sender, reward.rescale(_bDecimals)); emit Liquidate(owner, volume, cost, margin, timestamp, price, msg.sender, reward); } //================================================================================ // Helpers //================================================================================ /** * @dev Check if an address is a contract */ function _isContract(address addr) internal view returns (bool) { uint32 size; assembly { size := extcodesize(addr) } return size > 0; } /** * margin + unrealizedPnl *@dev margin ratio = -------------------------------------- * abs(volume) * price * multiplier * * volume cannot be zero */ function _calculateMarginRatio(int256 volume, int256 cost, uint256 price, uint256 margin) internal view returns (uint256) { int256 value = volume.mul(price).mul(_multiplier); uint256 ratio = margin.add(value.sub(cost)).div(value.abs()); return ratio; } /** * _tradersNetVolume * price * multiplier * @dev rate per block = ------------------------------------------- * coefficient * _liquidity */ function _updateCumuFundingRate(uint256 price) private { if (block.number > _cumuFundingRateBlock) { int256 rate; if (_liquidity != 0) { rate = _tradersNetVolume.mul(price).mul(_multiplier).mul(_fundingRateCoefficient).div(_liquidity); } else { rate = 0; } int256 delta = rate * (int256(block.number.sub(_cumuFundingRateBlock))); // overflow is intended _cumuFundingRate += delta; // overflow is intended _cumuFundingRateBlock = block.number; } } /** * @dev Check price signature */ function _checkPriceSignature(uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s) internal view { require(v == 27 || v == 28, "PerpetualPool: v not valid"); bytes32 message = keccak256(abi.encodePacked(_symbol, timestamp, price)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", message)); address signer = ecrecover(hash, v, r, s); require(signer == address(_oracle), "PerpetualPool: price not signed by oracle"); } /** * @dev Check price signature to verify if price is authorized, and update _price * only check/update once for one block */ function _updatePriceWithSignature( uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) internal { if (block.number != _lastPriceBlockNumber) { require(timestamp >= _lastPriceTimestamp, "PerpetualPool: price is not the newest"); require(block.timestamp - timestamp <= _priceDelayAllowance, "PerpetualPool: price is older than allowance"); _checkPriceSignature(timestamp, price, v, r, s); _price = price; _lastPriceTimestamp = timestamp; _lastPriceBlockNumber = block.number; } } /** * @dev Update price from on-chain Oracle */ function _updatePriceFromOracle() internal { require(_isContractOracle, "PerpetualPool: wrong type of orcale"); if (block.number != _lastPriceBlockNumber) { _price = _oracle.getPrice(); _lastPriceBlockNumber = block.number; } } /** * @dev safeTransferFrom for base token with deflation protection * Returns the actual received amount in base token (as base 10**18) */ function _deflationCompatibleSafeTransferFrom(address from, address to, uint256 amount) internal returns (uint256) { uint256 preBalance = _bToken.balanceOf(to); _bToken.safeTransferFrom(from, to, amount.rescale(_bDecimals)); uint256 curBalance = _bToken.balanceOf(to); uint256 a = curBalance.sub(preBalance); uint256 b = 10**18; uint256 c = a * b; require(c / b == a, "PreMiningPool: _deflationCompatibleSafeTransferFrom multiplication overflows"); uint256 actualReceivedAmount = c / (10 ** _bDecimals); return actualReceivedAmount; } } // 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 Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `amount` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @dev Emitted when `amount` tokens are moved from one account (`from`) to * another (`to`). * * Note that `amount` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the name. */ function symbol() external view returns (string memory); /** * @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); /** * @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 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 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 Moves `amount` tokens from `from` to `to` using the allowance mechanism. * `amount` is then deducted from the caller's allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title Deri Protocol non-fungible position token interface */ interface IPToken is IERC721 { /** * @dev Emitted when `owner`'s position is updated */ event Update( address indexed owner, int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin, uint256 lastUpdateTimestamp ); /** * @dev Position struct */ struct Position { // Position volume, long is positive and short is negative int256 volume; // Position cost, long position cost is positive, short position cost is negative int256 cost; // The last cumuFundingRate since last funding settlement for this position // The overflow for this value is intended int256 lastCumuFundingRate; // Margin associated with this position uint256 margin; // Last timestamp this position updated uint256 lastUpdateTimestamp; } /** * @dev Set pool address of position token * pool is the only controller of this contract * can only be called by current pool */ function setPool(address newPool) external; /** * @dev Returns address of current pool */ function pool() external view returns (address); /** * @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 total number of ever minted position tokens, including those burned */ function totalMinted() external view returns (uint256); /** * @dev Returns the total number of existent position tokens */ function totalSupply() external view returns (uint256); /** * @dev Returns if `owner` owns a position token in this contract */ function exists(address owner) external view returns (bool); /** * @dev Returns if position token of `tokenId` exists */ function exists(uint256 tokenId) external view returns (bool); /** * @dev Returns the position of owner `owner` * * `owner` must exist */ function getPosition(address owner) external view returns ( int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin, uint256 lastUpdateTimestamp ); /** * @dev Returns the position of token `tokenId` * * `tokenId` must exist */ function getPosition(uint256 tokenId) external view returns ( int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin, uint256 lastUpdateTimestamp ); /** * @dev Mint a position token for `owner` with intial margin of `margin` * * Can only be called by pool * `owner` cannot be zero address * `owner` must not exist before calling */ function mint(address owner, uint256 margin) external; /** * @dev Update the position token for `owner` * * Can only be called by pool * `owner` must exist */ function update( address owner, int256 volume, int256 cost, int256 lastCumuFundingRate, uint256 margin, uint256 lastUpdateTimestamp ) external; /** * @dev Burn the position token owned of `owner` * * Can only be called by pool * `owner` must exist */ function burn(address owner) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC20.sol"; /** * @title Deri Protocol liquidity provider token interface */ interface ILToken is IERC20 { /** * @dev Set the pool address of this LToken * pool is the only controller of this contract * can only be called by current pool */ function setPool(address newPool) external; /** * @dev Returns address of pool */ function pool() external view returns (address); /** * @dev Mint LToken to `account` of `amount` * * Can only be called by pool * `account` cannot be zero address */ function mint(address account, uint256 amount) external; /** * @dev Burn `amount` LToken of `account` * * Can only be called by pool * `account` cannot be zero address * `account` must owns at least `amount` LToken */ function burn(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @title Oracle interface */ interface IOracle { function getPrice() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @title Deri Protocol liquidator qualifier interface */ interface ILiquidatorQualifier { /** * @dev Check if `liquidator` is a qualified liquidator to call the `liquidate` function in PerpetualPool */ function isQualifiedLiquidator(address liquidator) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Deri Protocol migratable pool interface */ interface IMigratablePool { /** * @dev Emitted when migration is prepared * `source` pool will be migrated to `target` pool after `migrationTimestamp` */ event PrepareMigration(uint256 migrationTimestamp, address source, address target); /** * @dev Emmited when migration is executed * `source` pool is migrated to `target` pool */ event ExecuteMigration(uint256 migrationTimestamp, address source, address target); /** * @dev Set controller to `newController` * * can only be called by current controller or the controller has not been set */ function setController(address newController) external; /** * @dev Returns address of current controller */ function controller() external view returns (address); /** * @dev Returns the migrationTimestamp of this pool, zero means not set */ function migrationTimestamp() external view returns (uint256); /** * @dev Returns the destination pool this pool will migrate to after grace period * zero address means not set */ function migrationDestination() external view returns (address); /** * @dev Prepare a migration from this pool to `newPool` with `graceDays` as grace period * `graceDays` must be at least 3 days from now, allow users to verify the `newPool` code * * can only be called by controller */ function prepareMigration(address newPool, uint256 graceDays) external; /** * @dev Approve migration to `newPool` when grace period ends * after approvement, current pool will stop functioning * * can only be called by controller */ function approveMigration() external; /** * @dev Called from the `newPool` to migrate from `source` pool * the grace period of `source` pool must ends * current pool must be the destination pool set before grace period in the `source` pool * * can only be called by controller */ function executeMigration(address source) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IMigratablePool.sol"; /** * @title Deri Protocol PreMining PerpetualPool Interface */ interface IPreMiningPool is IMigratablePool { /** * @dev Emitted when `owner` add liquidity of `bAmount`, * and receive `lShares` liquidity token */ event AddLiquidity(address indexed owner, uint256 lShares, uint256 bAmount); /** * @dev Emitted when `owner` burn `lShares` of liquidity token, * and receive `bAmount` in base token */ event RemoveLiquidity(address indexed owner, uint256 lShares, uint256 bAmount); /** * @dev Initialize pool * * addresses: * bToken * lToken * * parameters: * minAddLiquidity * redemptionFeeRatio */ function initialize( string memory symbol_, address[2] calldata addresses_, uint256[2] calldata parameters_ ) external; /** * @dev Returns trading symbol */ function symbol() external view returns (string memory); /** * @dev Returns addresses of (bToken, pToken, lToken, oracle) in this pool */ function getAddresses() external view returns ( address bToken, address lToken ); /** * @dev Returns parameters of this pool */ function getParameters() external view returns ( uint256 minAddLiquidity, uint256 redemptionFeeRatio ); /** * @dev Returns currents state values of this pool */ function getStateValues() external view returns ( uint256 liquidity ); /** * @dev Add liquidity of `bAmount` in base token * * New liquidity provider token will be issued to the provider */ function addLiquidity(uint256 bAmount) external; /** * @dev Remove `lShares` of liquidity provider token * * The liquidity provider token will be burned and * the corresponding amount in base token will be sent to provider */ function removeLiquidity(uint256 lShares) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IMigratablePool.sol"; /** * @title Deri Protocol PerpetualPool Interface */ interface IPerpetualPool is IMigratablePool { /** * @dev Emitted when `owner` traded `tradeVolume` at `price` in pool */ event Trade(address indexed owner, int256 tradeVolume, uint256 price); /** * @dev Emitted when `owner` deposit margin of `bAmount` in base token */ event DepositMargin(address indexed owner, uint256 bAmount); /** * @dev Emitted when `owner` withdraw margin of `bAmount` in base token */ event WithdrawMargin(address indexed owner, uint256 bAmount); /** * @dev Emitted when `owner` add liquidity of `bAmount`, * and receive `lShares` liquidity token */ event AddLiquidity(address indexed owner, uint256 lShares, uint256 bAmount); /** * @dev Emitted when `owner` burn `lShares` of liquidity token, * and receive `bAmount` in base token */ event RemoveLiquidity(address indexed owner, uint256 lShares, uint256 bAmount); /** * @dev Emitted when `owner`'s position is liquidated */ event Liquidate( address indexed owner, int256 volume, int256 cost, uint256 margin, uint256 timestamp, uint256 price, address liquidator, uint256 reward ); /** * @dev Initialize pool * * addresses: * bToken * pToken * lToken * oracle * liquidatorQualifier * * parameters: * multiplier * feeRatio * minPoolMarginRatio * minInitialMarginRatio * minMaintenanceMarginRatio * minAddLiquidity * redemptionFeeRatio * fundingRateCoefficient * minLiquidationReward * maxLiquidationReward * liquidationCutRatio * priceDelayAllowance */ function initialize( string memory symbol_, address[5] calldata addresses_, uint256[12] calldata parameters_ ) external; /** * @dev Returns trading symbol */ function symbol() external view returns (string memory); /** * @dev Returns addresses of (bToken, pToken, lToken, oracle) in this pool */ function getAddresses() external view returns ( address bToken, address pToken, address lToken, address oracle, address liquidatorQualifier ); /** * @dev Returns parameters of this pool */ function getParameters() external view returns ( uint256 multiplier, uint256 feeRatio, uint256 minPoolMarginRatio, uint256 minInitialMarginRatio, uint256 minMaintenanceMarginRatio, uint256 minAddLiquidity, uint256 redemptionFeeRatio, uint256 fundingRateCoefficient, uint256 minLiquidationReward, uint256 maxLiquidationReward, uint256 liquidationCutRatio, uint256 priceDelayAllowance ); /** * @dev Returns currents state values of this pool */ function getStateValues() external view returns ( int256 cumuFundingRate, uint256 cumuFundingRateBlock, uint256 liquidity, int256 tradersNetVolume, int256 tradersNetCost ); /** * @dev Trade `tradeVolume` with pool while deposit margin of `bAmount` in base token * This function is the combination of `depositMargin` and `trade` * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function tradeWithMargin(int256 tradeVolume, uint256 bAmount) external; function tradeWithMargin( int256 tradeVolume, uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Trade `tradeVolume` with pool * * A trader must hold a Position Token (with sufficient margin in PToken) * before calling this function * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function trade(int256 tradeVolume) external; function trade( int256 tradeVolume, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Deposit margin of `bAmount` in base token * * If trader does not hold position token, a new position token will be minted * to trader with supplied margin * Otherwise, the position token of trader will be updated with added margin * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function depositMargin(uint256 bAmount) external; function depositMargin( uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Withdraw margin of `bAmount` in base token * * Trader must hold a position token * If trader holds any open position in position token, the left margin after withdraw * must be sufficient for the open position * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function withdrawMargin(uint256 bAmount) external; function withdrawMargin( uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Add liquidity of `bAmount` in base token * * New liquidity provider token will be issued to the provider * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function addLiquidity(uint256 bAmount) external; function addLiquidity( uint256 bAmount, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Remove `lShares` of liquidity provider token * * The liquidity provider token will be burned and * the corresponding amount in base token will be sent to provider * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function removeLiquidity(uint256 lShares) external; function removeLiquidity( uint256 lShares, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Liquidate the position owned by `owner` * Anyone can call this function to liquidate a position, as long as the liquidation line * is touched, the liquidator will be rewarded * * The first version is implemented with an on-chain oracle contract * The second version is implemented with off-chain price provider with signature */ function liquidate(address owner) external; function liquidate( address owner, uint256 timestamp, uint256 price, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../interface/IERC20.sol"; import "../math/UnsignedSafeMath.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 UnsignedSafeMath 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); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title Mixed safe math with base unit of 10**18 */ library MixedSafeMathWithUnit { uint256 constant UONE = 10**18; uint256 constant UMAX = 2**255 - 1; int256 constant IONE = 10**18; int256 constant IMIN = -2**255; //================================================================================ // Conversions //================================================================================ /** * @dev Convert uint256 to int256 */ function utoi(uint256 a) internal pure returns (int256) { require(a <= UMAX, "MixedSafeMathWithUnit: convert uint256 to int256 overflow"); int256 b = int256(a); return b; } /** * @dev Convert int256 to uint256 */ function itou(int256 a) internal pure returns (uint256) { require(a >= 0, "MixedSafeMathWithUnit: convert int256 to uint256 overflow"); uint256 b = uint256(a); return b; } /** * @dev Take abs of int256 */ function abs(int256 a) internal pure returns (int256) { require(a != IMIN, "MixedSafeMathWithUnit: int256 abs overflow"); if (a >= 0) { return a; } else { return -a; } } /** * @dev Take negation of int256 */ function neg(int256 a) internal pure returns (int256) { require(a != IMIN, "MixedSafeMathWithUnit: int256 negate overflow"); return -a; } //================================================================================ // Rescale and reformat //================================================================================ function _rescale(uint256 a, uint256 decimals1, uint256 decimals2) internal pure returns (uint256) { uint256 scale1 = 10 ** decimals1; uint256 scale2 = 10 ** decimals2; uint256 b = a * scale2; require(b / scale2 == a, "MixedSafeMathWithUnit: rescale uint256 overflow"); uint256 c = b / scale1; return c; } function _rescale(int256 a, uint256 decimals1, uint256 decimals2) internal pure returns (int256) { int256 scale1 = utoi(10 ** decimals1); int256 scale2 = utoi(10 ** decimals2); int256 b = a * scale2; require(b / scale2 == a, "MixedSafeMathWithUnit: rescale int256 overflow"); int256 c = b / scale1; return c; } /** * @dev Rescales a value from 10**18 base to 10**decimals base */ function rescale(uint256 a, uint256 decimals) internal pure returns (uint256) { return _rescale(a, 18, decimals); } function rescale(int256 a, uint256 decimals) internal pure returns (int256) { return _rescale(a, 18, decimals); } /** * @dev Reformat a value to be a valid 10**decimals base value * The formatted value is still in 10**18 base */ function reformat(uint256 a, uint256 decimals) internal pure returns (uint256) { return _rescale(_rescale(a, 18, decimals), decimals, 18); } function reformat(int256 a, uint256 decimals) internal pure returns (int256) { return _rescale(_rescale(a, 18, decimals), decimals, 18); } //================================================================================ // Addition //================================================================================ /** * @dev Addition: uint256 + uint256 */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "MixedSafeMathWithUnit: uint256 addition overflow"); return c; } /** * @dev Addition: int256 + int256 */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require( (b >= 0 && c >= a) || (b < 0 && c < a), "MixedSafeMathWithUnit: int256 addition overflow" ); return c; } /** * @dev Addition: uint256 + int256 * uint256(-b) will not overflow when b is IMIN */ function add(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return add(a, uint256(b)); } else { return sub(a, uint256(-b)); } } /** * @dev Addition: int256 + uint256 */ function add(int256 a, uint256 b) internal pure returns (int256) { return add(a, utoi(b)); } //================================================================================ // Subtraction //================================================================================ /** * @dev Subtraction: uint256 - uint256 */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "MixedSafeMathWithUnit: uint256 subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Subtraction: int256 - int256 */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require( (b >= 0 && c <= a) || (b < 0 && c > a), "MixedSafeMathWithUnit: int256 subtraction overflow" ); return c; } /** * @dev Subtraction: uint256 - int256 * uint256(-b) will not overflow when b is IMIN */ function sub(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return sub(a, uint256(b)); } else { return add(a, uint256(-b)); } } /** * @dev Subtraction: int256 - uint256 */ function sub(int256 a, uint256 b) internal pure returns (int256) { return sub(a, utoi(b)); } //================================================================================ // Multiplication //================================================================================ /** * @dev Multiplication: uint256 * uint256 */ 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, "MixedSafeMathWithUnit: uint256 multiplication overflow"); return c / UONE; } /** * @dev Multiplication: int256 * int256 */ 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 == IMIN), "MixedSafeMathWithUnit: int256 multiplication overflow"); int256 c = a * b; require(c / a == b, "MixedSafeMathWithUnit: int256 multiplication overflow"); return c / IONE; } /** * @dev Multiplication: uint256 * int256 */ function mul(uint256 a, int256 b) internal pure returns (uint256) { return mul(a, itou(b)); } /** * @dev Multiplication: int256 * uint256 */ function mul(int256 a, uint256 b) internal pure returns (int256) { return mul(a, utoi(b)); } //================================================================================ // Division //================================================================================ /** * @dev Division: uint256 / uint256 */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "MixedSafeMathWithUnit: uint256 division by zero"); uint256 c = a * UONE; require( c / UONE == a, "MixedSafeMathWithUnit: uint256 division internal multiplication overflow" ); uint256 d = c / b; return d; } /** * @dev Division: int256 / int256 */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "MixedSafeMathWithUnit: int256 division by zero"); int256 c = a * IONE; require( c / IONE == a, "MixedSafeMathWithUnit: int256 division internal multiplication overflow" ); require(!(c == IMIN && b == -1), "MixedSafeMathWithUnit: int256 division overflow"); int256 d = c / b; return d; } /** * @dev Division: uint256 / int256 */ function div(uint256 a, int256 b) internal pure returns (uint256) { return div(a, itou(b)); } /** * @dev Division: int256 / uint256 */ function div(int256 a, uint256 b) internal pure returns (int256) { return div(a, utoi(b)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../interface/IMigratablePool.sol"; /** * @dev Deri Protocol migratable pool implementation */ abstract contract MigratablePool is IMigratablePool { // Controller address address _controller; // Migration timestamp of this pool, zero means not set // Migration timestamp can only be set with a grace period at least 3 days, and the // `migrationDestination` pool address must be also set when setting migration timestamp, // users can use this grace period to verify the `migrationDestination` pool code uint256 _migrationTimestamp; // The new pool this pool will migrate to after grace period, zero address means not set address _migrationDestination; modifier _controller_() { require(msg.sender == _controller, "can only be called by current controller"); _; } /** * @dev See {IMigratablePool}.{setController} */ function setController(address newController) public override { require(newController != address(0), "MigratablePool: setController to 0 address"); require( _controller == address(0) || msg.sender == _controller, "MigratablePool: setController can only be called by current controller or not set" ); _controller = newController; } /** * @dev See {IMigratablePool}.{controller} */ function controller() public view override returns (address) { return _controller; } /** * @dev See {IMigratablePool}.{migrationTimestamp} */ function migrationTimestamp() public view override returns (uint256) { return _migrationTimestamp; } /** * @dev See {IMigratablePool}.{migrationDestination} */ function migrationDestination() public view override returns (address) { return _migrationDestination; } /** * @dev See {IMigratablePool}.{prepareMigration} */ function prepareMigration(address newPool, uint256 graceDays) public override _controller_ { require(newPool != address(0), "MigratablePool: prepareMigration to 0 address"); require(graceDays >= 3 && graceDays <= 365, "MigratablePool: graceDays must be 3-365 days"); _migrationTimestamp = block.timestamp + graceDays * 1 days; _migrationDestination = newPool; emit PrepareMigration(_migrationTimestamp, address(this), _migrationDestination); } /** * @dev See {IMigratablePool}.{approveMigration} * * This function will be implemented in inheriting contract * This function will change if there is an upgrade to existent pool */ // function approveMigration() public virtual override _controller_ {} /** * @dev See {IMigratablePool}.{executeMigration} * * This function will be implemented in inheriting contract * This function will change if there is an upgrade to existent pool */ // function executeMigration(address source) public virtual override _controller_ {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./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 `operator` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed operator, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables `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); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address); /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address); /** * @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 Gives permission to `operator` 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 operator, uint256 tokenId) external; /** * @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 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 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 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.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title Unsigned safe math */ library UnsignedSafeMath { /** * @dev Addition of unsigned integers, counterpart to `+` */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "UnsignedSafeMath: addition overflow"); return c; } /** * @dev Subtraction of unsigned integers, counterpart to `-` */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "UnsignedSafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Multiplication of unsigned integers, counterpart to `*` */ 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, "UnsignedSafeMath: multiplication overflow"); return c; } /** * @dev Division of unsigned integers, counterpart to `/` */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "UnsignedSafeMath: division by zero"); uint256 c = a / b; return c; } /** * @dev Modulo of unsigned integers, counterpart to `%` */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "UnsignedSafeMath: modulo by zero"); uint256 c = a % b; return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
* @dev See {IPerpetualPool}.{tradeWithMargin}/
function tradeWithMargin(int256 tradeVolume, uint256 bAmount) public override { _updatePriceFromOracle(); _tradeWithMargin(tradeVolume, bAmount); }
582,117
[ 1, 9704, 288, 45, 2173, 6951, 1462, 2864, 19654, 20077, 1190, 9524, 4004, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18542, 1190, 9524, 12, 474, 5034, 18542, 4545, 16, 2254, 5034, 324, 6275, 13, 1071, 3849, 288, 203, 3639, 389, 2725, 5147, 1265, 23601, 5621, 203, 3639, 389, 20077, 1190, 9524, 12, 20077, 4545, 16, 324, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; import "./IPermissions.sol"; import "../token/IRusd.sol"; /// @title Core Interface /// @author Ring Protocol interface ICore is IPermissions { // ----------- Events ----------- event RusdUpdate(address indexed _rusd); event RingUpdate(address indexed _ring); event GenesisGroupUpdate(address indexed _genesisGroup); event RingAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setRusd(address token) external; function setRing(address token) external; function setGenesisGroup(address _genesisGroup) external; function allocateRing(address to, uint256 amount) external; // ----------- Genesis Group only state changing api ----------- function completeGenesisGroup() external; // ----------- Getters ----------- function rusd() external view returns (IRusd); function ring() external view returns (IERC20); function genesisGroup() external view returns (address); function hasGenesisGroupCompleted() external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; /// @title Permissions interface /// @author Ring Protocol interface IPermissions { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> 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: GPL-2.0-or-later pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "./SafeMathCopy.sol"; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMathCopy for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /** * @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 SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap 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: GPL-2.0-or-later pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; import "../external/Decimal.sol"; /// @title generic oracle interface for Ring Protocol /// @author Ring Protocol interface IOracle { // ----------- Getters ----------- function read() external view returns (Decimal.D256 memory, bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "./UniswapPCVDeposit.sol"; /// @title implementation for an ETH Uniswap LP PCV Deposit /// @author Ring Protocol contract ERC20UniswapPCVDeposit is UniswapPCVDeposit { using Address for address payable; using SafeCast for uint256; /// @notice ETH Uniswap PCV Deposit constructor /// @param _core Ring Core for reference /// @param _pool Uniswap V3 Pool to deposit to /// @param _nft Uniswap V3 position manager to reference /// @param _router Uniswap Router /// @param _oracle oracle for reference constructor( address _core, address _pool, address _nft, address _router, address _oracle, int24 _tickLower, int24 _tickUpper ) UniswapPCVDeposit(_core, _pool, _nft, _router, _oracle) { tickLower = _tickLower; tickUpper = _tickUpper; } /// @notice deposit tokens into the PCV allocation function deposit() external payable override whenNotPaused { uint256 erc20AmountBalance = IERC20(token()).balanceOf(address(this)); // include any ERC20 dust from prior LP uint256 rusdAmount = _getAmountRusdToDeposit(erc20AmountBalance); _addLiquidity(erc20AmountBalance, rusdAmount); _burnRusdHeld(); // burn any RUSD dust from LP emit Deposit(msg.sender, erc20AmountBalance); } /// @notice collect fee income function collect() public override whenNotPaused returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = nft.collect( INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: uint128(-1), amount1Max: uint128(-1) }) ); emit Collect(address(this), amount0, amount1); } function _removeLiquidity(uint128 liquidity) internal override { uint256 endOfTime = uint256(-1); nft.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: tokenId, liquidity: liquidity, amount0Min: 0, amount1Min: 0, deadline: endOfTime }) ); collect(); } function _transferWithdrawn(address to) internal override { uint256 balance = IERC20(token()).balanceOf(address(this)); TransferHelper.safeTransfer(token(), to, balance); } function _addLiquidity(uint256 erc20Amount, uint256 rusdAmount) internal { _mintRusd(rusdAmount); uint256 endOfTime = uint256(-1); address rusdAddress = address(rusd()); address tokenAddress = token(); (address token0, address token1) = rusdAddress < tokenAddress ? (rusdAddress, tokenAddress) : (tokenAddress, rusdAddress); (uint256 amount0Desired, uint256 amount1Desired) = rusdAddress < tokenAddress ? (rusdAmount, erc20Amount) : (erc20Amount, rusdAmount); if (tokenId == 0) { (tokenId, , ,) = nft.mint( INonfungiblePositionManager.MintParams({ token0: token0, token1: token1, tickLower: tickLower, tickUpper: tickUpper, amount0Desired: amount0Desired, amount1Desired: amount1Desired, amount0Min: 0, amount1Min: 0, recipient: address(this), deadline: endOfTime, fee: fee }) ); } else { if (amount0Desired > 0 || amount1Desired > 0) { nft.increaseLiquidity( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amount0Desired, amount1Desired: amount1Desired, amount0Min: 0, amount1Min: 0, deadline: endOfTime }) ); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title a PCV Deposit interface /// @author Ring Protocol interface IPCVDeposit { // ----------- Events ----------- event Deposit(address indexed _from, uint256 _amount); event Collect(address indexed _from, uint256 _amount0, uint256 _amount1); event Withdrawal( address indexed _caller, address indexed _to, uint256 _amount ); // ----------- State changing api ----------- function deposit() external payable; function collect() external returns (uint256 amount0, uint256 amount1); // ----------- PCV Controller only state changing api ----------- function withdraw(address to, uint256 amount) external; function burnAndReset(uint24 _fee, int24 _tickLower, int24 _tickUpper) external; // ----------- Getters ----------- function fee() external view returns (uint24); function tickLower() external view returns (int24); function tickUpper() external view returns (int24); function totalLiquidity() external view returns (uint128); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "./IPCVDeposit.sol"; import "../refs/UniRef.sol"; /// @title abstract implementation for Uniswap LP PCV Deposit /// @author Ring Protocol abstract contract UniswapPCVDeposit is IPCVDeposit, UniRef { using Decimal for Decimal.D256; using SafeCast for uint256; uint24 public override fee = 500; int24 public override tickLower; int24 public override tickUpper; /// @notice Uniswap PCV Deposit constructor /// @param _core Ring Core for reference /// @param _pool Uniswap Pair to deposit to /// @param _nft Uniswap V3 position manager to reference /// @param _router Uniswap Router /// @param _oracle oracle for reference constructor( address _core, address _pool, address _nft, address _router, address _oracle ) UniRef(_core, _pool, _nft, _router, _oracle) {} /// @notice withdraw tokens from the PCV allocation /// @param amountLiquidity withdrawn /// @param to the address to send PCV to function withdraw(address to, uint256 amountLiquidity) external override onlyPCVController whenNotPaused { require( amountLiquidity <= liquidityOwned(), "UniswapPCVDeposit: Insufficient underlying" ); _removeLiquidity(amountLiquidity.toUint128()); _transferWithdrawn(to); _burnRusdHeld(); emit Withdrawal(msg.sender, to, amountLiquidity); } /// @notice burn old position and reset parameters of new position /// @param _fee of new position /// @param _tickLower of new position /// @param _tickUpper of new position function burnAndReset(uint24 _fee, int24 _tickLower, int24 _tickUpper) external override onlyPCVController whenNotPaused { nft.burn(tokenId); tokenId = 0; fee = _fee; tickLower = _tickLower; tickUpper = _tickUpper; } /// @notice returns total value of PCV in the Deposit function totalLiquidity() public view override returns (uint128) { return liquidityOwned(); } function _getAmountRusdToDeposit(uint256 amountToken) internal view returns (uint256 amountRusd) { return peg().mul(amountToken).asUint256(); } function _removeLiquidity(uint128 liquidity) internal virtual; function _transferWithdrawn(address to) internal virtual; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "./ICoreRef.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /// @title A Reference to Core /// @author Ring Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private _core; /// @notice CoreRef constructor /// @param newCore Ring Core to reference constructor(address newCore) { _core = ICore(newCore); } modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier ifBurnerSelf() { if (_core.isBurner(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require( _core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier onlyRusd() { require(msg.sender == address(rusd()), "CoreRef: Caller is not RUSD"); _; } modifier onlyGenesisGroup() { require( msg.sender == _core.genesisGroup(), "CoreRef: Caller is not GenesisGroup" ); _; } modifier nonContract() { require(!Address.isContract(msg.sender), "CoreRef: Caller is a contract"); _; } /// @notice set new Core reference address /// @param _newCore the new core address function setCore(address _newCore) external override onlyGovernor { _core = ICore(_newCore); emit CoreUpdate(_newCore); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Rusd contract referenced by Core /// @return IRusd implementation address function rusd() public view override returns (IRusd) { return _core.rusd(); } /// @notice address of the Ring contract referenced by Core /// @return IERC20 implementation address function ring() public view override returns (IERC20) { return _core.ring(); } /// @notice rusd balance of contract /// @return rusd amount held function rusdBalance() public view override returns (uint256) { return rusd().balanceOf(address(this)); } /// @notice ring balance of contract /// @return ring amount held function ringBalance() public view override returns (uint256) { return ring().balanceOf(address(this)); } function _burnRusdHeld() internal { rusd().burn(rusdBalance()); } function _mintRusd(uint256 amount) internal { rusd().mint(address(this), amount); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Ring Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed _core); // ----------- Governor only state changing api ----------- function setCore(address _newCore) external; function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function rusd() external view returns (IRusd); function ring() external view returns (IERC20); function rusdBalance() external view returns (uint256); function ringBalance() external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; import "../oracle/IOracle.sol"; /// @title OracleRef interface /// @author Ring Protocol interface IOracleRef { // ----------- Events ----------- event OracleUpdate(address indexed _oracle); // ----------- Governor only state changing API ----------- function setOracle(address _oracle) external; // ----------- Getters ----------- function oracle() external view returns (IOracle); function peg() external view returns (Decimal.D256 memory); function invert(Decimal.D256 calldata price) external pure returns (Decimal.D256 memory); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; /// @title UniRef interface /// @author Ring Protocol interface IUniRef { // ----------- Events ----------- event PoolUpdate(address indexed _pool); // ----------- Governor only state changing api ----------- function setPool(address _pool) external; // ----------- Getters ----------- function nft() external view returns (INonfungiblePositionManager); function router() external view returns (ISwapRouter); function pool() external view returns (IUniswapV3Pool); function tokenId() external view returns (uint256); function token() external view returns (address); function liquidityOwned() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "./IOracleRef.sol"; import "./CoreRef.sol"; /// @title Reference to an Oracle /// @author Ring Protocol /// @notice defines some utilities around interacting with the referenced oracle abstract contract OracleRef is IOracleRef, CoreRef { using Decimal for Decimal.D256; /// @notice the oracle reference by the contract IOracle public override oracle; /// @notice OracleRef constructor /// @param _core Ring Core to reference /// @param _oracle oracle to reference constructor(address _core, address _oracle) CoreRef(_core) { _setOracle(_oracle); } /// @notice sets the referenced oracle /// @param _oracle the new oracle to reference function setOracle(address _oracle) external override onlyGovernor { _setOracle(_oracle); } /// @notice invert a peg price /// @param price the peg price to invert /// @return the inverted peg as a Decimal /// @dev the inverted peg would be X per RUSD function invert(Decimal.D256 memory price) public pure override returns (Decimal.D256 memory) { return Decimal.one().div(price); } /// @notice the peg price of the referenced oracle /// @return the peg as a Decimal /// @dev the peg is defined as RUSD per X with X being ETH, dollars, etc function peg() public view override returns (Decimal.D256 memory) { (Decimal.D256 memory _peg, bool valid) = oracle.read(); require(valid, "OracleRef: oracle invalid"); return _peg; } function _setOracle(address _oracle) internal { oracle = IOracle(_oracle); emit OracleUpdate(_oracle); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "./OracleRef.sol"; import "./IUniRef.sol"; /// @title A Reference to Uniswap /// @author Ring Protocol /// @notice defines some modifiers and utilities around interacting with Uniswap /// @dev the uniswap v3 pool should be RUSD and another asset abstract contract UniRef is IUniRef, OracleRef { using Decimal for Decimal.D256; using SafeMathCopy for uint256; using SafeMathCopy for uint160; uint256 private constant FIXED_POINT_GRANULARITY = 2**96; /// @notice the Uniswap V3 position manager INonfungiblePositionManager public override nft; /// @notice the Uniswap router contract ISwapRouter public override router; /// @notice the referenced Uniswap V3 pool contract IUniswapV3Pool public override pool; /// @notice the referenced Uniswap V3 pool position id uint256 public override tokenId; /// @notice UniRef constructor /// @param _core Ring Core to reference /// @param _pool Uniswap V3 pool to reference /// @param _nft Uniswap V3 position manager to reference /// @param _router Uniswap Router to reference /// @param _oracle oracle to reference constructor( address _core, address _pool, address _nft, address _router, address _oracle ) OracleRef(_core, _oracle) { _setupPool(_pool); nft = INonfungiblePositionManager(_nft); router = ISwapRouter(_router); _approveTokenToRouter(address(rusd())); _approveTokenToRouter(token()); _approveTokenToNFT(address(rusd())); _approveTokenToNFT(token()); } /// @notice set the new pool contract /// @param _pool the new pool /// @dev also approves the router for the new pool token and underlying token function setPool(address _pool) external override onlyGovernor { _setupPool(_pool); _approveTokenToRouter(token()); _approveTokenToNFT(token()); } /// @notice the address of the non-rusd underlying token function token() public view override returns (address) { address token0 = pool.token0(); if (address(rusd()) == token0) { return pool.token1(); } return token0; } /// @notice amount of pool liquidity owned by this contract /// @return amount of liquidity function liquidityOwned() public view override returns (uint128) { (, , , , , , , uint128 liquidity, , , , ) = nft.positions(tokenId); return liquidity; } /// @notice returns true if price is below the peg /// @dev counterintuitively checks if peg < price because price is reported as RUSD per X function _isBelowPeg(Decimal.D256 memory peg) internal view returns (bool) { Decimal.D256 memory price = _getUniswapPrice(); return peg.lessThan(price); } /// @notice approves a token for the router function _approveTokenToRouter(address _token) internal { uint256 maxTokens = uint256(-1); TransferHelper.safeApprove(_token, address(router), maxTokens); } /// @notice approves a token for the position manager function _approveTokenToNFT(address _token) internal { uint256 maxTokens = uint256(-1); TransferHelper.safeApprove(_token, address(nft), maxTokens); } function _setupPool(address _pool) internal { pool = IUniswapV3Pool(_pool); emit PoolUpdate(_pool); } /// @notice get uniswap price /// @return price reported as Rusd per X function _getUniswapPrice() internal view returns (Decimal.D256 memory) { (uint160 sqrtPriceX96, , , , , , ) = pool.slot0(); if (token() < address(rusd())) { return Decimal.ratio(sqrtPriceX96, FIXED_POINT_GRANULARITY).pow(2); } else { return Decimal.ratio(FIXED_POINT_GRANULARITY, sqrtPriceX96).pow(2); } } /// @notice return current percent distance from peg /// @dev will return Decimal.zero() if above peg function _getDistanceToPeg() internal view returns (Decimal.D256 memory distance) { Decimal.D256 memory price = _getUniswapPrice(); return _deviationBelowPeg(price, peg()); } /// @notice get deviation from peg as a percent given price /// @dev will return Decimal.zero() if above peg function _deviationBelowPeg( Decimal.D256 memory price, Decimal.D256 memory peg ) internal pure returns (Decimal.D256 memory) { // If price <= peg, then RUSD is more expensive and above peg // In this case we can just return zero for deviation if (price.lessThanOrEqualTo(peg)) { return Decimal.zero(); } Decimal.D256 memory delta = price.sub(peg, "Impossible underflow"); return delta.div(peg); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title RUSD stablecoin interface /// @author Ring Protocol interface IRusd is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address incentive) external; // ----------- Getters ----------- function incentiveContract() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <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.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // 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, 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-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryPayments.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryPayments, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPeripheryPayments { /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. /// @param amountMinimum The minimum amount of WETH9 to unwrap /// @param recipient The address receiving ETH function unwrapWETH9(uint256 amountMinimum, address recipient) external payable; /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } }
@notice ETH Uniswap PCV Deposit constructor @param _core Ring Core for reference @param _pool Uniswap V3 Pool to deposit to @param _nft Uniswap V3 position manager to reference @param _router Uniswap Router @param _oracle oracle for reference
) UniswapPCVDeposit(_core, _pool, _nft, _router, _oracle) { tickLower = _tickLower; tickUpper = _tickUpper; }
10,058,253
[ 1, 1584, 44, 1351, 291, 91, 438, 453, 22007, 4019, 538, 305, 3885, 225, 389, 3644, 25463, 4586, 364, 2114, 225, 389, 6011, 1351, 291, 91, 438, 776, 23, 8828, 358, 443, 1724, 358, 225, 389, 82, 1222, 1351, 291, 91, 438, 776, 23, 1754, 3301, 358, 2114, 225, 389, 10717, 1351, 291, 91, 438, 9703, 225, 389, 280, 16066, 20865, 364, 2114, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 1351, 291, 91, 438, 3513, 58, 758, 1724, 24899, 3644, 16, 389, 6011, 16, 389, 82, 1222, 16, 389, 10717, 16, 389, 280, 16066, 13, 288, 203, 3639, 4024, 4070, 273, 389, 6470, 4070, 31, 203, 3639, 4024, 5988, 273, 389, 6470, 5988, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* ____ __ __ ____ / __ \____ _____/ /_____ / /_ / __ \_________ ____ / /_/ / __ \/ ___/ //_/ _ \/ __/ / / / / ___/ __ \/ __ \ / _, _/ /_/ / /__/ ,< / __/ /_ / /_/ / / / /_/ / /_/ / /_/ |_|\____/\___/_/|_|\___/\__/ /_____/_/ \____/ .___/ /_/ That's right you haters, this is ROCKET DROP: the ONLY farming solution that let's you stake ANY kind of token for ANY kind of yield. This will be the bedrock of the Rocket Bunny and Corlibri community. If you haven't read our Medium articles, I HIGHLY suggest you do so. There's also some pretty cool diagrams that you can check out in order to understand what this is. If you got any questions, feel free to join our tg group listed here. Anyone can help answer questions, or just @ the dev, sycore0, and he (I) will get back to you ASAP. I always answer, even if you're trying to sell me shit. Much love my fellow humans, and enjoy. web: rocketbunny.io tg: @RocketBunnyChat */ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/VendingMachine.sol pragma solidity 0.6.12; // VendingMachine distributes the ERC20 rewards based on staked LP to each user. // // Cloned from https://github.com/SashimiProject/sashimiswap/blob/master/contracts/MasterChef.sol // Modified by LTO Network to work for non-mintable ERC20. contract RocketDropV1 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 ERC20s // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accERC20PerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accERC20PerShare` (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 lastRewardBlock; // Last block number that ERC20s distribution occurs. uint256 accERC20PerShare; // Accumulated ERC20s per share, times 1e36. IERC20 rewardToken; // pool specific reward token. uint256 startBlock; // pool specific block number when rewards start uint256 endBlock; // pool specific block number when rewards end uint256 rewardPerBlock; // pool specific reward per block uint256 paidOut; // total paid out by pool uint256 tokensStaked; // allows the same token to be staked across different pools uint256 gasAmount; // eth fee charged on deposits and withdrawals (per pool) uint256 minStake; // minimum tokens allowed to be staked uint256 maxStake; // max tokens allowed to be staked address payable partnerTreasury; // allows eth fee to be split with a partner on transfer uint256 partnerPercent; // eth fee percent of partner split, 2 decimals (ie 10000 = 100.00%, 1002 = 10.02%) } // default eth fee for deposits and withdrawals uint256 public gasAmount = 2000000000000000; address payable public treasury; IERC20 public accessToken; uint256 public accessTokenMin; bool public accessTokenRequired = false; // vars to keep track of $bunny IERC20 public rocketBunny; //uint256 rocketBunnyYield; //uint256 public rocketBunnyHeld; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; 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(IERC20 rocketBunnyAddress) public { rocketBunny = rocketBunnyAddress; treasury = msg.sender; } // Number of LP pools function poolLength() external view returns (uint256) { return poolInfo.length; } function currentBlock() external view returns (uint256) { return block.number; } // Fund the farm, increase the end block function initialFund(uint256 _pid, uint256 _amount, uint256 _startBlock) public { require(poolInfo[_pid].startBlock == 0, "initialFund: initial funding already complete"); IERC20 erc20; erc20 = poolInfo[_pid].rewardToken; erc20.safeTransferFrom(address(msg.sender), address(this), _amount); poolInfo[_pid].lastRewardBlock = _startBlock; poolInfo[_pid].startBlock = _startBlock; poolInfo[_pid].endBlock = _startBlock.add(_amount.div(poolInfo[_pid].rewardPerBlock)); } // Fund the farm, increase the end block function fundMore(uint256 _pid, uint256 _amount) public { require(block.number < poolInfo[_pid].endBlock, "fundMore: pool closed or use initialFund() first"); IERC20 erc20; erc20 = poolInfo[_pid].rewardToken; erc20.safeTransferFrom(address(msg.sender), address(this), _amount); poolInfo[_pid].endBlock += _amount.div(poolInfo[_pid].rewardPerBlock); } // Add a new lp to the pool. Can only be called by the owner. // rewards are calculated per pool, so you can add the same lpToken multiple times function add(IERC20 _lpToken, IERC20 _rewardToken, uint256 _rewardPerBlock, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } //### poolInfo.push(PoolInfo({ lpToken: _lpToken, lastRewardBlock: 0, accERC20PerShare: 0, rewardToken: _rewardToken, startBlock: 0, endBlock: 0, rewardPerBlock: _rewardPerBlock, paidOut: 0, tokensStaked: 0, gasAmount: gasAmount, // defaults to global gas/eth fee minStake: 0, maxStake: ~uint256(0), partnerTreasury: treasury, partnerPercent: 0 })); } //#### // Update the given pool's ERC20 reward per block. Can only be called by the owner. function set(uint256 _pid, uint256 _rewardPerBlock, bool _withUpdate) public onlyOwner { updatePool(_pid); // prevents taking existing rewards from current stakers poolInfo[_pid].rewardPerBlock = _rewardPerBlock; if (_withUpdate) { updatePool(_pid); } } function minStake(uint256 _pid, uint256 _minStake) public onlyOwner { poolInfo[_pid].minStake = _minStake; } function maxStake(uint256 _pid, uint256 _maxStake) public onlyOwner { poolInfo[_pid].maxStake = _maxStake; } // View function to see deposited LP for a user. function deposited(uint256 _pid, address _user) external view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; return user.amount; } // View function to see pending ERC20s for a user. function pending(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accERC20PerShare = pool.accERC20PerShare; uint256 lpSupply = pool.tokensStaked; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 lastBlock = block.number < pool.endBlock ? block.number : pool.endBlock; uint256 nrOfBlocks = lastBlock.sub(pool.lastRewardBlock); uint256 erc20Reward = nrOfBlocks.mul(pool.rewardPerBlock); accERC20PerShare = accERC20PerShare.add(erc20Reward.mul(1e36).div(lpSupply)); } return user.amount.mul(accERC20PerShare).div(1e36).sub(user.rewardDebt); } // View function for total reward the farm has yet to pay out. function totalPending(uint256 _pid) external view returns (uint256) { if (block.number <= poolInfo[_pid].startBlock) { return 0; } uint256 lastBlock = block.number < poolInfo[_pid].endBlock ? block.number : poolInfo[_pid].endBlock; return poolInfo[_pid].rewardPerBlock.mul(lastBlock - poolInfo[_pid].startBlock).sub(poolInfo[_pid].paidOut); } // Update reward variables 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]; uint256 lastBlock = block.number < pool.endBlock ? block.number : pool.endBlock; if (lastBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.tokensStaked; if (lpSupply == 0) { pool.lastRewardBlock = lastBlock; return; } uint256 nrOfBlocks = lastBlock.sub(pool.lastRewardBlock); uint256 erc20Reward = nrOfBlocks.mul(pool.rewardPerBlock); pool.accERC20PerShare = pool.accERC20PerShare.add(erc20Reward.mul(1e36).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to VendingMachine for ERC20 allocation. function deposit(uint256 _pid, uint256 _amount) public payable { if(accessTokenRequired){ require(accessToken.balanceOf(msg.sender) >= accessTokenMin, 'Must have minimum amount of access token!'); } PoolInfo storage pool = poolInfo[_pid]; uint256 poolGasAmount = pool.gasAmount; require(msg.value >= poolGasAmount, 'Correct gas amount must be sent!'); require(_amount >= pool.minStake && _amount <= pool.maxStake, 'Min/Max stake required!'); UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt); erc20Transfer(msg.sender, _pid, pendingAmount); } uint256 startTokenBalance = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); uint256 endTokenBalance = pool.lpToken.balanceOf(address(this)); uint256 trueDepositedTokens = endTokenBalance.sub(startTokenBalance); user.amount = user.amount.add(trueDepositedTokens); pool.tokensStaked = pool.tokensStaked.add(trueDepositedTokens); user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36); // remit eth fee according to partner status if (pool.partnerPercent == 0) { treasury.transfer(msg.value); } else { uint256 totalAmount = msg.value; uint256 partnerAmount = totalAmount.mul(pool.partnerPercent).div(10000); uint256 treasuryAmount = totalAmount.sub(partnerAmount); treasury.transfer(treasuryAmount); pool.partnerTreasury.transfer(partnerAmount); } emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from VendingMachine. function withdraw(uint256 _pid, uint256 _amount) public payable { if(accessTokenRequired){ require(accessToken.balanceOf(msg.sender) >= accessTokenMin, 'Must have minimum amount of access token!'); } PoolInfo storage pool = poolInfo[_pid]; uint256 poolGasAmount = pool.gasAmount; require(msg.value >= poolGasAmount, 'Correct gas amount must be sent!'); UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: can't withdraw more than deposit"); updatePool(_pid); uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt); erc20Transfer(msg.sender, _pid, pendingAmount); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36); if(_amount > 0){ pool.lpToken.safeTransfer(address(msg.sender), _amount); pool.tokensStaked = pool.tokensStaked.sub(_amount); } // remit eth fee according to partner status if (pool.partnerPercent == 0) { treasury.transfer(msg.value); } else { uint256 totalAmount = msg.value; uint256 partnerAmount = totalAmount.mul(pool.partnerPercent).div(10000); uint256 treasuryAmount = totalAmount.sub(partnerAmount); treasury.transfer(treasuryAmount); pool.partnerTreasury.transfer(partnerAmount); } 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); pool.tokensStaked = pool.tokensStaked.sub(user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Transfer ERC20 and update the required ERC20 to payout all rewards function erc20Transfer(address _to, uint256 _pid, uint256 _amount) internal { IERC20 erc20; erc20 = poolInfo[_pid].rewardToken; erc20.transfer(_to, _amount); poolInfo[_pid].paidOut += _amount; } // adjust default/global gas fee function adjustGasGlobal(uint256 newgas) public onlyOwner { gasAmount = newgas; } // access token settings function changeAccessToken(IERC20 newToken) public onlyOwner { accessToken = newToken; } function changeAccessMin(uint256 newMin) public onlyOwner { accessTokenMin = newMin; } function changeAccessTknReq(bool setting) public onlyOwner { accessTokenRequired = setting; } // adjust pool gas/eth fee function adjustPoolGas(uint256 _pid, uint256 newgas) public onlyOwner { poolInfo[_pid].gasAmount = newgas; } function transferExtraBunny(address _recipient) public onlyOwner { uint256 length = poolInfo.length; uint256 bunnyHeld; uint256 bunnyBalance = rocketBunny.balanceOf(address(this)); for (uint256 pid = 0; pid < length; ++pid) { if(poolInfo[pid].lpToken == rocketBunny){ bunnyHeld = bunnyHeld.add(poolInfo[pid].tokensStaked); } } uint256 bunnyYield = bunnyBalance.sub(bunnyHeld); rocketBunny.transfer(_recipient, bunnyYield); } // change global treasury function changeTreasury(address payable newTreasury) public onlyOwner { treasury = newTreasury; } function changePartnerTreasury(uint256 _pid, address payable newTreasury) public onlyOwner { poolInfo[_pid].partnerTreasury = newTreasury; } function changePartnerPercent(uint256 _pid, uint256 newPercent) public onlyOwner { poolInfo[_pid].partnerPercent = newPercent; } function transfer() public onlyOwner { treasury.transfer(address(this).balance); } }
change global treasury
function changeTreasury(address payable newTreasury) public onlyOwner { treasury = newTreasury; }
6,014,002
[ 1, 3427, 2552, 9787, 345, 22498, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 56, 266, 345, 22498, 12, 2867, 8843, 429, 394, 56, 266, 345, 22498, 13, 1071, 1338, 5541, 288, 203, 3639, 9787, 345, 22498, 273, 394, 56, 266, 345, 22498, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0xf9d3F8C046C9a45081123d768FF0189E01A5bca2/sources/OnChainGovernanceImpl1_flat.sol
pauser role state variables
contract OnChainGovernanceImpl is AccessControl { using SafeMath for uint256; bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant MEMBER_ROLE = keccak256("MEMBER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); address public constant ZEROES = address(0); address public owner; address public nextOwner; uint256 public constant MAXIMUM_QUORUM_PERCENTAGE = 100; uint256 public constant MINIMUM_QUORUM_PERCENTAGE = 1; uint256 public constant MINIMUM_QUORUM_VOTERS = 1; uint256 public constant MINIMUM_TOKENS_TO_VOTE = .01 ether; ERC20Snapshottable public votingToken; mapping(address => bool) public enabledERC20Token; Quorum public quorum = Quorum(50, 1200, 1); mapping(uint256 => Quorum) quorums; Fees public fee = Fees(.01 ether, 10, address(this)); mapping(uint256 => VotingData) public voteContent; mapping(address => mapping(uint256 => bool)) voted; mapping(address => mapping(uint256 => string)) justifications; mapping(uint256 => uint256) public yay; mapping(uint256 => uint256) public yayCount; mapping(uint256 => uint256) public nay; mapping(uint256 => uint256) public nayCount; mapping(uint256 => uint256) public totalVotes; uint256 public voteRaisedIndex; uint256 public lastVoteRaised = block.number - MINIMUM_BLOCKS_BETWEEN_VOTES_RAISED; mapping(uint256 => bool) public voteRaised; mapping(uint256 => VoteResult) public voteDecided; mapping(uint256 => bool) public voteResolved; bool public paused; bool public mintingEnabled; constructor() { owner = msg.sender; _setupRole(OWNER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setupRole(MEMBER_ROLE, msg.sender); _setupRole(PAUSER_ROLE, msg.sender); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(ADMIN_ROLE, OWNER_ROLE); _setRoleAdmin(MEMBER_ROLE, OWNER_ROLE); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); votingToken = ERC20Snapshottable(address(0xab0732343Cd9cF90DaBeE45747Cbd0d0320327d4)); enabledERC20Token[address(0xab0732343Cd9cF90DaBeE45747Cbd0d0320327d4)] = true; } event VoteRaised(VotingData data); function proposeSpendMATIC(address payable _receiver, uint256 _amount, string memory _voteTitle, string memory _voteContent) public onlyRole(MEMBER_ROLE) onlySender returns (uint256){ require(votingToken.balanceOf(msg.sender) >= fee.min, "Not enough of ERC20!"); require(address(this).balance >= _amount, "Not enough MATIC!"); require(_amount > 0, "Send something1!"); require(!paused, "Paused"); require(block.number >(lastVoteRaised + MINIMUM_BLOCKS_BETWEEN_VOTES_RAISED), "Vote too soon!"); voteRaisedIndex += 1; voteContent[voteRaisedIndex] = VotingData( _voteTitle, _voteContent, _receiver, _amount, votingToken.snapshot(), block.number, VoteType.MATICSpend, ZEROES, quorum, fee, new address[](0), new uint256[](0), new bytes[](0) ); uint256 percent = votingToken.balanceOf(msg.sender) / 100 * (fee.percent); uint256 rawFee = percent > fee.min ? percent : fee.min; votingToken.transferFrom(msg.sender, fee.recipient, rawFee); voteDecided[voteRaisedIndex] = VoteResult.VoteOpen; voteRaised[voteRaisedIndex] = true; quorums[voteRaisedIndex] = quorum; lastVoteRaised = block.number; emit VoteRaised(voteContent[voteRaisedIndex]); return voteRaisedIndex; } function proposeAddERC20Token(address payable _receiver, address _erc20Token, string memory _voteTitle, string memory _voteContent) public onlyRole(MEMBER_ROLE) onlySender returns (uint256) { require(votingToken.balanceOf(msg.sender) >= fee.min, "Not enough of Voting Token to raise vote!"); require(!enabledERC20Token[_erc20Token], "Token already approved!"); require(_erc20Token != address(0), "Pls use valid ERC20!"); require(!paused, "Paused"); require(block.number >(lastVoteRaised + MINIMUM_BLOCKS_BETWEEN_VOTES_RAISED), "Vote too soon!"); voteRaisedIndex += 1; voteContent[voteRaisedIndex] = VotingData( _voteTitle, _voteContent, _receiver, 0, votingToken.snapshot(), block.number, VoteType.ERC20New, _erc20Token, quorum, fee, new address[](0), new uint256[](0), new bytes[](0) ); uint256 percent = votingToken.balanceOf(msg.sender) / 100 * (fee.percent); uint256 rawFee = percent > fee.min ? percent : fee.min; votingToken.transferFrom(msg.sender, fee.recipient, rawFee); voteDecided[voteRaisedIndex] = VoteResult.VoteOpen; voteRaised[voteRaisedIndex] = true; quorums[voteRaisedIndex] = quorum; lastVoteRaised = block.number; emit VoteRaised(voteContent[voteRaisedIndex]); return voteRaisedIndex; } function proposeSpendERC20Token(address payable _receiver, uint256 _amount, address _erc20Token, string memory _voteTitle, string memory _voteContent) public onlyRole(MEMBER_ROLE) onlySender returns (uint256){ require(votingToken.balanceOf(msg.sender) >= fee.min, "Not enough of Voting Token to raise vote!"); require(enabledERC20Token[_erc20Token], "Token not approved!"); require(ERC20(_erc20Token).balanceOf(address(this)) >= _amount, "Not enough of ERC20!"); require(_amount > 0, "Send something!"); require(!paused, "Paused"); require(block.number >(lastVoteRaised + MINIMUM_BLOCKS_BETWEEN_VOTES_RAISED), "Vote too soon!"); voteRaisedIndex += 1; voteContent[voteRaisedIndex] = VotingData( _voteTitle, _voteContent, _receiver, _amount, votingToken.snapshot(), block.number, VoteType.ERC20Spend, _erc20Token, quorum, fee, new address[](0), new uint256[](0), new bytes[](0) ); uint256 percent = votingToken.balanceOf(msg.sender) / 100 * (fee.percent); uint256 rawFee = percent > fee.min ? percent : fee.min; votingToken.transferFrom(msg.sender, fee.recipient, rawFee); voteDecided[voteRaisedIndex] = VoteResult.VoteOpen; voteRaised[voteRaisedIndex] = true; quorums[voteRaisedIndex] = quorum; lastVoteRaised = block.number; emit VoteRaised(voteContent[voteRaisedIndex]); return voteRaisedIndex; } function proposeUpdateQuorum(address payable _recipient, Quorum memory _newQuorum, string memory _voteTitle, string memory _voteContent) public onlyRole(MEMBER_ROLE) onlySender returns (uint256){ require(votingToken.balanceOf(msg.sender) >= fee.min, "Not enough of ERC20!"); validateQuorum(_newQuorum); require(!paused, "Paused"); require(block.number >(lastVoteRaised + MINIMUM_BLOCKS_BETWEEN_VOTES_RAISED), "Vote too soon!"); voteRaisedIndex += 1; voteContent[voteRaisedIndex] = VotingData( _voteTitle, _voteContent, _recipient, 0, votingToken.snapshot(), block.number, VoteType.UpdateQuorum, ZEROES, _newQuorum, fee, new address[](0), new uint256[](0), new bytes[](0) ); uint256 percent = votingToken.balanceOf(msg.sender) / 100 * (fee.percent); uint256 rawFee = percent > fee.min ? percent : fee.min; votingToken.transferFrom(msg.sender, fee.recipient, rawFee); voteDecided[voteRaisedIndex] = VoteResult.VoteOpen; voteRaised[voteRaisedIndex] = true; quorums[voteRaisedIndex] = quorum; lastVoteRaised = block.number; emit VoteRaised(voteContent[voteRaisedIndex]); return voteRaisedIndex; } function proposeUpdateFees(address payable _recipient, Fees memory _newFees, string memory _voteTitle, string memory _voteContent) public onlyRole(MEMBER_ROLE) onlySender returns (uint256){ require(votingToken.balanceOf(msg.sender) >= fee.min, "Not enough of ERC20!"); validateFees(_newFees); require(!paused, "Paused"); require(block.number >(lastVoteRaised + MINIMUM_BLOCKS_BETWEEN_VOTES_RAISED), "Vote too soon!"); voteRaisedIndex += 1; voteContent[voteRaisedIndex] = VotingData( _voteTitle, _voteContent, _recipient, 0, votingToken.snapshot(), block.number, VoteType.UpdateFees, ZEROES, quorum, _newFees, new address[](0), new uint256[](0), new bytes[](0) ); uint256 percent = votingToken.balanceOf(msg.sender) / 100 * (fee.percent); uint256 rawFee = percent > fee.min ? percent : fee.min; votingToken.transferFrom(msg.sender, fee.recipient, rawFee); voteDecided[voteRaisedIndex] = VoteResult.VoteOpen; voteRaised[voteRaisedIndex] = true; quorums[voteRaisedIndex] = quorum; lastVoteRaised = block.number; emit VoteRaised(voteContent[voteRaisedIndex]); return voteRaisedIndex; } function proposeContractCall(address payable _recipient, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory _voteTitle, string memory _voteContent) public onlyRole(MEMBER_ROLE) returns (uint256) { require(votingToken.balanceOf(msg.sender) >= fee.min, "Not enough of ERC20!"); require(!paused, "Paused"); require(block.number >(lastVoteRaised + MINIMUM_BLOCKS_BETWEEN_VOTES_RAISED), "Vote too soon!"); require(targets.length == values.length, "Governor: invalid proposal length"); require(targets.length == calldatas.length, "Governor: invalid proposal length"); require(targets.length > 0, "Governor: empty proposal"); voteRaisedIndex += 1; voteContent[voteRaisedIndex] = VotingData( _voteTitle, _voteContent, _recipient, 0, block.number, votingToken.snapshot(), VoteType.UpdateQuorum, ZEROES, quorum, fee, targets, values, calldatas ); uint256 percent = votingToken.balanceOf(msg.sender) / 100 * (fee.percent); uint256 rawFee = percent > fee.min ? percent : fee.min; votingToken.transferFrom(msg.sender, fee.recipient, rawFee); voteDecided[voteRaisedIndex] = VoteResult.VoteOpen; voteRaised[voteRaisedIndex] = true; quorums[voteRaisedIndex] = quorum; lastVoteRaised = block.number; return voteRaisedIndex; } event Yay(VotingData data); event Nay(VotingData data); event Voted(address voter, VoteResult result, string justification); function vote(uint256 id, bool _yay, string memory justification) public onlySender onlyRole(MEMBER_ROLE){ require(votingToken.balanceOf(msg.sender) >= MINIMUM_TOKENS_TO_VOTE, "Not enough of Voting token to vote. Need .01"); require(voteRaised[id], "vote not yet raised!"); require(!voted[msg.sender][id], "Sender already voted"); require(voteDecided[id] == VoteResult.VoteOpen, "vote already decided!"); require(!paused, "Paused"); uint256 balanceOf = votingToken.balanceOfAt(msg.sender, voteContent[id].snapshotId); require(balanceOf > 0, "No voting token!"); if (_yay) { yay[id] += balanceOf; totalVotes[id] += balanceOf; yayCount[id] += 1; nay[id] += balanceOf; totalVotes[id] += balanceOf; nayCount[id] += 1; } if (yay[id] * 100 > (quorums[id].quorumPercentage * totalVotes[id]) && yay[id] > quorums[id].staticQuorumTokens && quorums[id].minVoters <= yayCount[id]){ emit Yay(voteContent[id]); voteDecided[id] = VoteResult.Passed; } else if ((nay[id] * 100 > (quorums[id].quorumPercentage * totalVotes[id])) && nay[id] > quorums[id].staticQuorumTokens && quorums[id].minVoters <= nayCount[id]) { emit Nay(voteContent[id]); voteDecided[id] = VoteResult.Discarded; } voted[msg.sender][id] = true; justifications[msg.sender][id] = justification; emit Voted(msg.sender, voteDecided[id], justification); } function vote(uint256 id, bool _yay, string memory justification) public onlySender onlyRole(MEMBER_ROLE){ require(votingToken.balanceOf(msg.sender) >= MINIMUM_TOKENS_TO_VOTE, "Not enough of Voting token to vote. Need .01"); require(voteRaised[id], "vote not yet raised!"); require(!voted[msg.sender][id], "Sender already voted"); require(voteDecided[id] == VoteResult.VoteOpen, "vote already decided!"); require(!paused, "Paused"); uint256 balanceOf = votingToken.balanceOfAt(msg.sender, voteContent[id].snapshotId); require(balanceOf > 0, "No voting token!"); if (_yay) { yay[id] += balanceOf; totalVotes[id] += balanceOf; yayCount[id] += 1; nay[id] += balanceOf; totalVotes[id] += balanceOf; nayCount[id] += 1; } if (yay[id] * 100 > (quorums[id].quorumPercentage * totalVotes[id]) && yay[id] > quorums[id].staticQuorumTokens && quorums[id].minVoters <= yayCount[id]){ emit Yay(voteContent[id]); voteDecided[id] = VoteResult.Passed; } else if ((nay[id] * 100 > (quorums[id].quorumPercentage * totalVotes[id])) && nay[id] > quorums[id].staticQuorumTokens && quorums[id].minVoters <= nayCount[id]) { emit Nay(voteContent[id]); voteDecided[id] = VoteResult.Discarded; } voted[msg.sender][id] = true; justifications[msg.sender][id] = justification; emit Voted(msg.sender, voteDecided[id], justification); } } else { function vote(uint256 id, bool _yay, string memory justification) public onlySender onlyRole(MEMBER_ROLE){ require(votingToken.balanceOf(msg.sender) >= MINIMUM_TOKENS_TO_VOTE, "Not enough of Voting token to vote. Need .01"); require(voteRaised[id], "vote not yet raised!"); require(!voted[msg.sender][id], "Sender already voted"); require(voteDecided[id] == VoteResult.VoteOpen, "vote already decided!"); require(!paused, "Paused"); uint256 balanceOf = votingToken.balanceOfAt(msg.sender, voteContent[id].snapshotId); require(balanceOf > 0, "No voting token!"); if (_yay) { yay[id] += balanceOf; totalVotes[id] += balanceOf; yayCount[id] += 1; nay[id] += balanceOf; totalVotes[id] += balanceOf; nayCount[id] += 1; } if (yay[id] * 100 > (quorums[id].quorumPercentage * totalVotes[id]) && yay[id] > quorums[id].staticQuorumTokens && quorums[id].minVoters <= yayCount[id]){ emit Yay(voteContent[id]); voteDecided[id] = VoteResult.Passed; } else if ((nay[id] * 100 > (quorums[id].quorumPercentage * totalVotes[id])) && nay[id] > quorums[id].staticQuorumTokens && quorums[id].minVoters <= nayCount[id]) { emit Nay(voteContent[id]); voteDecided[id] = VoteResult.Discarded; } voted[msg.sender][id] = true; justifications[msg.sender][id] = justification; emit Voted(msg.sender, voteDecided[id], justification); } function vote(uint256 id, bool _yay, string memory justification) public onlySender onlyRole(MEMBER_ROLE){ require(votingToken.balanceOf(msg.sender) >= MINIMUM_TOKENS_TO_VOTE, "Not enough of Voting token to vote. Need .01"); require(voteRaised[id], "vote not yet raised!"); require(!voted[msg.sender][id], "Sender already voted"); require(voteDecided[id] == VoteResult.VoteOpen, "vote already decided!"); require(!paused, "Paused"); uint256 balanceOf = votingToken.balanceOfAt(msg.sender, voteContent[id].snapshotId); require(balanceOf > 0, "No voting token!"); if (_yay) { yay[id] += balanceOf; totalVotes[id] += balanceOf; yayCount[id] += 1; nay[id] += balanceOf; totalVotes[id] += balanceOf; nayCount[id] += 1; } if (yay[id] * 100 > (quorums[id].quorumPercentage * totalVotes[id]) && yay[id] > quorums[id].staticQuorumTokens && quorums[id].minVoters <= yayCount[id]){ emit Yay(voteContent[id]); voteDecided[id] = VoteResult.Passed; } else if ((nay[id] * 100 > (quorums[id].quorumPercentage * totalVotes[id])) && nay[id] > quorums[id].staticQuorumTokens && quorums[id].minVoters <= nayCount[id]) { emit Nay(voteContent[id]); voteDecided[id] = VoteResult.Discarded; } voted[msg.sender][id] = true; justifications[msg.sender][id] = justification; emit Voted(msg.sender, voteDecided[id], justification); } function resolveVote(uint256 id) public onlyRole(ADMIN_ROLE) { require(!paused, "Paused"); require(voteDecided[id] != VoteResult.VoteOpen, "vote is still open!"); require(!voteResolved[id], "Vote has already been resolved"); require(voteContent[id].blockStart + MINIMUM_BLOCKS_BEFORE_VOTE_RESOLVED < block.number, "Need to wait to resolve"); if(voteDecided[id] == VoteResult.Discarded || voteDecided[id] == VoteResult.VetoedByOwner) { voteResolved[id] = true; } else if (voteDecided[id] == VoteResult.Passed || voteDecided[id] == VoteResult.PassedByOwner) { VotingData memory _data = voteContent[id]; if (_data.voteType == VoteType.ERC20New) { enabledERC20Token[_data.erc20Token] = true; ERC20(_data.erc20Token).transfer(_data.receiver, _data.amount); _data.receiver.transfer(_data.amount); quorum = _data.quorum; fee = _data.fees; _execute(_data.targets, _data.values, _data.calldatas); } voteResolved[id] = true; } } event ContractCallExecuted(bool success, bytes returndata); function resolveVote(uint256 id) public onlyRole(ADMIN_ROLE) { require(!paused, "Paused"); require(voteDecided[id] != VoteResult.VoteOpen, "vote is still open!"); require(!voteResolved[id], "Vote has already been resolved"); require(voteContent[id].blockStart + MINIMUM_BLOCKS_BEFORE_VOTE_RESOLVED < block.number, "Need to wait to resolve"); if(voteDecided[id] == VoteResult.Discarded || voteDecided[id] == VoteResult.VetoedByOwner) { voteResolved[id] = true; } else if (voteDecided[id] == VoteResult.Passed || voteDecided[id] == VoteResult.PassedByOwner) { VotingData memory _data = voteContent[id]; if (_data.voteType == VoteType.ERC20New) { enabledERC20Token[_data.erc20Token] = true; ERC20(_data.erc20Token).transfer(_data.receiver, _data.amount); _data.receiver.transfer(_data.amount); quorum = _data.quorum; fee = _data.fees; _execute(_data.targets, _data.values, _data.calldatas); } voteResolved[id] = true; } } event ContractCallExecuted(bool success, bytes returndata); function resolveVote(uint256 id) public onlyRole(ADMIN_ROLE) { require(!paused, "Paused"); require(voteDecided[id] != VoteResult.VoteOpen, "vote is still open!"); require(!voteResolved[id], "Vote has already been resolved"); require(voteContent[id].blockStart + MINIMUM_BLOCKS_BEFORE_VOTE_RESOLVED < block.number, "Need to wait to resolve"); if(voteDecided[id] == VoteResult.Discarded || voteDecided[id] == VoteResult.VetoedByOwner) { voteResolved[id] = true; } else if (voteDecided[id] == VoteResult.Passed || voteDecided[id] == VoteResult.PassedByOwner) { VotingData memory _data = voteContent[id]; if (_data.voteType == VoteType.ERC20New) { enabledERC20Token[_data.erc20Token] = true; ERC20(_data.erc20Token).transfer(_data.receiver, _data.amount); _data.receiver.transfer(_data.amount); quorum = _data.quorum; fee = _data.fees; _execute(_data.targets, _data.values, _data.calldatas); } voteResolved[id] = true; } } event ContractCallExecuted(bool success, bytes returndata); function resolveVote(uint256 id) public onlyRole(ADMIN_ROLE) { require(!paused, "Paused"); require(voteDecided[id] != VoteResult.VoteOpen, "vote is still open!"); require(!voteResolved[id], "Vote has already been resolved"); require(voteContent[id].blockStart + MINIMUM_BLOCKS_BEFORE_VOTE_RESOLVED < block.number, "Need to wait to resolve"); if(voteDecided[id] == VoteResult.Discarded || voteDecided[id] == VoteResult.VetoedByOwner) { voteResolved[id] = true; } else if (voteDecided[id] == VoteResult.Passed || voteDecided[id] == VoteResult.PassedByOwner) { VotingData memory _data = voteContent[id]; if (_data.voteType == VoteType.ERC20New) { enabledERC20Token[_data.erc20Token] = true; ERC20(_data.erc20Token).transfer(_data.receiver, _data.amount); _data.receiver.transfer(_data.amount); quorum = _data.quorum; fee = _data.fees; _execute(_data.targets, _data.values, _data.calldatas); } voteResolved[id] = true; } } event ContractCallExecuted(bool success, bytes returndata); } else if (_data.voteType == VoteType.ERC20Spend) { } else if (_data.voteType == VoteType.MATICSpend) { } else if (_data.voteType == VoteType.UpdateQuorum) { } else if (_data.voteType == VoteType.UpdateFees) { } else if (_data.voteType == VoteType.ContractCall) { function _execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas ) internal virtual { string memory errorMessage = "Governor: call reverted without message"; for (uint256 i = 0; i < targets.length; ++i) { Address.verifyCallResult(success, returndata, errorMessage); emit ContractCallExecuted(success, returndata); } } function _execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas ) internal virtual { string memory errorMessage = "Governor: call reverted without message"; for (uint256 i = 0; i < targets.length; ++i) { Address.verifyCallResult(success, returndata, errorMessage); emit ContractCallExecuted(success, returndata); } } (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]); function validateQuorum(Quorum memory _quorum) internal pure { require(_quorum.quorumPercentage <= MAXIMUM_QUORUM_PERCENTAGE && _quorum.quorumPercentage >= MINIMUM_QUORUM_PERCENTAGE, "Quorum Percentage out of 0-100"); require(_quorum.minVoters >= MINIMUM_QUORUM_VOTERS, "Quorum requires 1 voter"); } function validateFees(Fees memory _fees) internal pure { require(_fees.percent <= MAXIMUM_QUORUM_PERCENTAGE && _fees.percent >= MINIMUM_QUORUM_PERCENTAGE, "Quorum Percentage out of 0-100"); } event Veto(uint256 id); event ForcePass(uint256 id); function ownerVetoProposal(uint256 proposalIndex) public onlyRole(OWNER_ROLE) { require(voteRaised[proposalIndex], "vote not raised!"); require(!voteResolved[proposalIndex], "Vote resolved!"); voteDecided[proposalIndex] = VoteResult.VetoedByOwner; emit Veto(proposalIndex); } function ownerPassProposal(uint256 proposalIndex) public onlyRole(OWNER_ROLE) { require(voteRaised[proposalIndex], "vote not raised!"); require(!voteResolved[proposalIndex], "Vote resolved!"); voteDecided[proposalIndex] = VoteResult.PassedByOwner; emit ForcePass(proposalIndex); } function pauseMinting() public onlyRole(PAUSER_ROLE) { mintingEnabled = false; } function unpauseMinting() public onlyRole(PAUSER_ROLE) { mintingEnabled = true; } function pause() public onlyRole(PAUSER_ROLE) { paused = true; } function unpause() public onlyRole(PAUSER_ROLE) { paused = false; } function revokeMember(address _newRaiser) public onlyRole(ADMIN_ROLE) onlySender { require(!paused, "Paused"); revokeRole(MEMBER_ROLE, _newRaiser); } function addMember(address _newRaiser) public onlyRole(ADMIN_ROLE) onlySender { require(!paused, "Paused"); _setupRole(MEMBER_ROLE, _newRaiser); } function promoteNextOwner(address _nextOwner) public onlyRole(OWNER_ROLE) { require(_nextOwner != owner, "next owner == owner"); require(_nextOwner != ZEROES, "Must promote valid governance"); nextOwner = _nextOwner; } function acceptOwnership() public onlyRole(MEMBER_ROLE) { require(msg.sender != owner, "Owner cannot take own ownership"); require(nextOwner == msg.sender, "Caller not nominated"); _setupRole(OWNER_ROLE, msg.sender); revokeRole(OWNER_ROLE, owner); owner = msg.sender; nextOwner = ZEROES; } modifier onlySender { require(msg.sender == tx.origin, "No smart contracts"); _; } event Received(address from, uint amount); receive() external payable { if (msg.value > 0) emit Received(msg.sender, msg.value); } fallback() external payable { if (msg.value > 0) emit Received(msg.sender, msg.value); } }
4,755,032
[ 1, 8774, 1355, 2478, 919, 3152, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2755, 3893, 43, 1643, 82, 1359, 2828, 353, 24349, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 377, 203, 565, 1731, 1578, 1071, 5381, 531, 22527, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 29602, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 25969, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 15468, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 18990, 6271, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 19630, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 15662, 4714, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 4066, 4714, 67, 16256, 8863, 203, 377, 203, 565, 1758, 1071, 5381, 18449, 3991, 273, 1758, 12, 20, 1769, 203, 377, 203, 565, 1758, 1071, 3410, 31, 203, 565, 1758, 1071, 1024, 5541, 31, 203, 377, 203, 565, 2254, 5034, 1071, 5381, 4552, 18605, 67, 3500, 916, 2799, 67, 3194, 19666, 2833, 273, 2130, 31, 203, 565, 2254, 5034, 1071, 5381, 6989, 18605, 67, 3500, 916, 2799, 67, 3194, 19666, 2833, 273, 404, 31, 203, 565, 2254, 5034, 1071, 5381, 6989, 18605, 67, 3500, 916, 2799, 67, 58, 1974, 11367, 273, 404, 31, 203, 565, 2254, 5034, 1071, 5381, 6989, 18605, 67, 8412, 55, 67, 4296, 67, 16169, 1448, 273, 263, 1611, 225, 2437, 31, 203, 203, 203, 565, 4232, 39, 3462, 4568, 2121, 1071, 331, 17128, 1345, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 3696, 654, 39, 3462, 1345, 31, 203, 203, 565, 4783, 16105, 1071, 31854, 273, 4783, 16105, 12, 3361, 2 ]
./partial_match/1/0x208A7284032d94C1eeD40dC431Db3BACAa5d749a/sources/Pool.sol
/ Can modify account state
contract Permission is Setters { bytes32 private constant FILE = "Permission"; modifier onlyFrozenOrFluid(address account) { Require.that( statusOf(account) != Account.Status.Locked, FILE, "Not frozen or fluid" ); _; } modifier onlyFrozenOrLocked(address account) { Require.that( statusOf(account) != Account.Status.Fluid, FILE, "Not frozen or locked" ); _; } modifier initializer() { Require.that( !isInitialized(implementation()), FILE, "Already initialized" ); initialized(implementation()); _; } }
2,807,945
[ 1, 19, 4480, 5612, 2236, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8509, 353, 1000, 5432, 288, 203, 203, 565, 1731, 1578, 3238, 5381, 7527, 273, 315, 5041, 14432, 203, 203, 27699, 565, 9606, 1338, 42, 9808, 1162, 2340, 1911, 12, 2867, 2236, 13, 288, 203, 3639, 12981, 18, 19056, 12, 203, 5411, 1267, 951, 12, 4631, 13, 480, 6590, 18, 1482, 18, 8966, 16, 203, 5411, 7527, 16, 203, 5411, 315, 1248, 12810, 578, 27112, 6, 203, 3639, 11272, 203, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 42, 9808, 1162, 8966, 12, 2867, 2236, 13, 288, 203, 3639, 12981, 18, 19056, 12, 203, 5411, 1267, 951, 12, 4631, 13, 480, 6590, 18, 1482, 18, 2340, 1911, 16, 203, 5411, 7527, 16, 203, 5411, 315, 1248, 12810, 578, 8586, 6, 203, 3639, 11272, 203, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 12562, 1435, 288, 203, 3639, 12981, 18, 19056, 12, 203, 5411, 401, 291, 11459, 12, 30810, 1435, 3631, 203, 5411, 7527, 16, 203, 5411, 315, 9430, 6454, 6, 203, 3639, 11272, 203, 203, 3639, 6454, 12, 30810, 10663, 203, 203, 3639, 389, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xCB456983E9Cd47146b5817fC5c93D5B3B90BcD7B/sources/browser/StandardToken.sol
digest bytes to bytes32
bytes32 _digest;
9,776,140
[ 1, 10171, 1731, 358, 1731, 1578, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1731, 1578, 389, 10171, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x8f9A8Dc65A423C7Dec9261aA6010DB738407C879/sources/PumpFarm.sol
ETH/Token convert to uniswap liq amount, remove latter.
uint256 tmpAmount;
3,584,965
[ 1, 1584, 44, 19, 1345, 1765, 358, 640, 291, 91, 438, 4501, 85, 3844, 16, 1206, 23740, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 1853, 6275, 31, 2398, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; import "./IToken.sol"; import "./MatryxSystem.sol"; import "./LibTournament.sol"; contract MatryxPlatform { using SafeMath for uint256; struct Info { address system; address token; address owner; } struct Data { uint256 totalBalance; // total allocated mtx balance of the platform mapping(address=>uint256) tournamentBalance; // maps tournament addresses to tournament balances mapping(bytes32=>uint256) commitBalance; // maps commit hashes to commit mtx balances mapping(address=>LibTournament.TournamentData) tournaments; // maps tournament addresses to tournament structs mapping(bytes32=>LibTournament.SubmissionData) submissions; // maps submission identifier to submission struct address[] allTournaments; // all matryx tournament addresses mapping(bytes32=>LibCommit.Commit) commits; // maps commit hashes to commits mapping(bytes32=>LibCommit.Group) groups; // maps group hashes to group structs mapping(bytes32=>bytes32) commitHashes; // maps content hashes to commit hashes mapping(bytes32=>bytes32[]) commitToSubmissions; // maps commits to submission created from them mapping(bytes32=>LibCommit.CommitWithdrawalStats) commitWithdrawalStats; // maps commit hash to withdrawal stats mapping(bytes32=>uint256) commitClaims; // timestamp of content hash claim mapping(address=>bool) whitelist; // user whitelist mapping(address=>bool) blacklist; // user blacklist } Info info; // slot 0 Data data; // slot 3 address pendingOwner; constructor(address system, address token) public { info.system = system; info.token = token; info.owner = msg.sender; } /// @dev /// 1) Uses msg.sender to ask MatryxSystem for the type of library this call should be forwarded to /// 2) Uses this library type to lookup (in its own storage) the name of the library /// 3) Uses this name to ask MatryxSystem for the address of the contract (under this platform's version) /// 4) Uses name and signature to ask MatryxSystem for the data necessary to modify the incoming calldata /// so as to be appropriate for the associated library call /// 5) Makes a delegatecall to the library address given by MatryxSystem with the library-appropriate calldata function () external { uint256 version = IMatryxSystem(info.system).getVersion(); bytes32 libName = IMatryxSystem(info.system).getLibraryName(msg.sender); bool isForwarded = libName != bytes32("LibPlatform"); assembly { if isForwarded { calldatacopy(0, 0x24, 0x20) // get injected version from calldata version := mload(0) // overwrite version var } } address libAddress = IMatryxSystem(info.system).getContract(version, libName); assembly { // constants let offset := 0x100000000000000000000000000000000000000000000000000000000 let res let ptr := mload(0x40) // scratch space for calldata let system := sload(info_slot) // load info.system address // get fnData from system mstore(ptr, mul(0x3b15aabf, offset)) // getContractMethod(uint256,bytes32,bytes32) mstore(add(ptr, 0x04), version) // arg 0 - version mstore(add(ptr, 0x24), libName) // arg 1 - library name mstore(add(ptr, 0x44), 0) // zero out uninitialized data calldatacopy(add(ptr, 0x44), 0, 0x04) // arg 2 - fn selector res := call(gas, system, 0, ptr, 0x64, 0, 0) // call system.getContractMethod returndatacopy(ptr, 0, returndatasize) // copy fnData into ptr if iszero(res) { revert(ptr, returndatasize) } // safety check let ptr2 := add(ptr, mload(ptr)) // ptr2 is pointer to start of fnData let m_injParams := add(ptr2, mload(add(ptr2, 0x20))) // mem loc injected params let injParams_len := mload(m_injParams) // num injected params m_injParams := add(m_injParams, 0x20) // first injected param let m_dynParams := add(ptr2, mload(add(ptr2, 0x40))) // memory location of start of dynamic params let dynParams_len := mload(m_dynParams) // num dynamic params m_dynParams := add(m_dynParams, 0x20) // first dynamic param // forward calldata to library ptr := add(ptr, returndatasize) // shift ptr to new scratch space mstore(ptr, mload(ptr2)) // forward call with modified selector ptr2 := add(ptr, 0x04) // copy of ptr for keeping track of injected params mstore(ptr2, address) // inject platform mstore(add(ptr2, 0x20), caller) // inject msg.sender let cdOffset := 0x04 // calldata offset, after signature if isForwarded { mstore(ptr2, caller) // overwrite injected platform with sender calldatacopy(add(ptr2, 0x20), 0x04, 0x20) // overwrite injected sender with address from forwarder cdOffset := add(cdOffset, 0x40) // shift calldata offset for injected address and version } ptr2 := add(ptr2, 0x40) // shift ptr2 to account for injected addresses for { let i := 0 } lt(i, injParams_len) { i := add(i, 1) } { // loop through injected params and insert let injParam := mload(add(m_injParams, mul(i, 0x20))) // get injected param slot mstore(ptr2, injParam) // store injected params into next slot ptr2 := add(ptr2, 0x20) // shift ptr2 by a word for each injected } calldatacopy(ptr2, cdOffset, sub(calldatasize, cdOffset)) // copy calldata after injected data storage for { let i := 0 } lt(i, dynParams_len) { i := add(i, 1) } { // loop through params and update dynamic param locations let idx := mload(add(m_dynParams, mul(i, 0x20))) // get dynParam index in parameters let loc := add(ptr2, mul(idx, 0x20)) // get location in memory of dynParam mstore(loc, add(mload(loc), mul(add(injParams_len, 2), 0x20))) // shift dynParam location by num injected } // calculate size of forwarded call let size := add(0x04, sub(calldatasize, cdOffset)) // calldatasize minus injected size := add(size, mul(add(injParams_len, 2), 0x20)) // add size of injected res := delegatecall(gas, libAddress, ptr, size, 0, 0) // delegatecall to library returndatacopy(ptr, 0, returndatasize) // copy return data into ptr for returning if iszero(res) { revert(ptr, returndatasize) } // safety check return(ptr, returndatasize) // return forwarded call returndata } } modifier onlyOwner() { require(msg.sender == info.owner, "Must be Platform owner"); _; } /// @dev Enables address to accept ownership of the platform /// @param newOwner New owner address function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0)); pendingOwner = newOwner; } /// @dev Accepts ownership transfer function acceptOwnership() external { require(msg.sender == pendingOwner); info.owner = pendingOwner; pendingOwner = address(0); } /// @dev Sets the Token address /// @param token New token address function upgradeToken(address token) external onlyOwner { IToken(info.token).upgrade(data.totalBalance); require(IToken(token).balanceOf(address(this)) == data.totalBalance, "Token address must match upgraded token"); info.token = token; } /// @dev Withdraws any unallocated ERC20 tokens from Platform /// @param token ERC20 token address to use function withdrawTokens(address token) external onlyOwner { uint256 balance = IToken(token).balanceOf(address(this)); // if current token, check if any extraneous tokens if (token == info.token) { balance = balance.sub(data.totalBalance); } require(IToken(token).transfer(msg.sender, balance), "Transfer failed"); } } interface IMatryxPlatform { event TournamentCreated(address indexed tournament, address indexed creator); event TournamentUpdated(address indexed tournament); event TournamentBountyAdded(address indexed tournament, address indexed donor, uint256 amount); event RoundCreated(address indexed tournament, uint256 roundIndex); event RoundUpdated(address indexed tournament, uint256 roundIndex); event RoundWinnersSelected(address indexed tournament, uint256 roundIndex); event SubmissionCreated(address indexed tournament, bytes32 submissionHash, address indexed creator); event SubmissionRewarded(address indexed tournament, bytes32 submissionHash); event GroupMemberAdded(bytes32 indexed commitHash, address indexed user); event CommitClaimed(bytes32 commitHash); event CommitCreated(bytes32 indexed parentHash, bytes32 commitHash, address indexed creator, bool indexed isFork); function transferOwnership(address newOwner) external; function acceptOwnership() external; function upgradeToken(address token) external; function withdrawTokens(address token) external; function getInfo() external view returns (MatryxPlatform.Info memory); function isTournament(address tournament) external view returns (bool); function isCommit(bytes32 commitHash) external view returns (bool); function isSubmission(bytes32 submissionHash) external view returns (bool); function getTotalBalance() external view returns (uint256); function getTournamentCount() external view returns (uint256); function getTournaments() external view returns (address[] memory); function getSubmission(bytes32 submissionHash) external view returns (LibTournament.SubmissionData memory); function setUserBlacklisted(address user, bool isBlacklisted) external; function createTournament(LibTournament.TournamentDetails calldata, LibTournament.RoundDetails calldata) external returns (address); }
loop through params and update dynamic param locations
for { let i := 0 } lt(i, dynParams_len) { i := add(i, 1) } {
12,843,208
[ 1, 6498, 3059, 859, 471, 1089, 5976, 579, 7838, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 364, 288, 2231, 277, 519, 374, 289, 13489, 12, 77, 16, 19417, 1370, 67, 1897, 13, 288, 277, 519, 527, 12, 77, 16, 404, 13, 289, 288, 540, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // LC->07.08.2018 facts гл_предл language=Russian { arity=3 //violation_score=-5 generic return=boolean } #define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{} #region Предлог_В // ------------------- С ПРЕДЛОГОМ 'В' --------------------------- #region Предложный // Глаголы и отглагольные части речи, присоединяющие // предложное дополнение с предлогом В и сущ. в предложном падеже. wordentry_set Гл_В_Предл = { rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль // вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб rus_verbs:воевать{}, // Воевал во Франции. rus_verbs:устать{}, // Устали в дороге? rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения. rus_verbs:решить{}, // Что решат в правительстве? rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает. rus_verbs:обстоять{}, // В действительности же дело обстояло не так. rus_verbs:подыматься{}, rus_verbs:поехать{}, // поедем в такси! rus_verbs:уехать{}, // он уехал в такси rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей rus_verbs:ОБЛАЧИТЬ{}, rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло. rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ) rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ) rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ) rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ) rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ) rus_verbs:ЗАМАЯЧИТЬ{}, rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ) rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ) rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ) rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ) rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ) rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ) rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ) rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ) rus_verbs:ПоТЕРЯТЬ{}, rus_verbs:УТЕРЯТЬ{}, rus_verbs:РАСТЕРЯТЬ{}, rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.) rus_verbs:СОМКНУТЬСЯ{}, rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ) rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ) rus_verbs:ВЫСТОЯТЬ{}, rus_verbs:ПОСТОЯТЬ{}, rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ) rus_verbs:ВЗВЕШИВАТЬ{}, rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ) прилагательное:быстрый{}, // Кисель быстр в приготовлении rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень rus_verbs:призывать{}, rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ) rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ) rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ) rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ) rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ) rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ) rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ) rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ) rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ) rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ) rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ) rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ) rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ) rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ) rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ) rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ) rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ) rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ) rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ) rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ) rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ) rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ) rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ) rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ) rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ) rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ) rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ) rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ) инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан глагол:проводить{ вид:несоверш }, деепричастие:проводя{}, rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл) rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл) rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл) rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл) rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл) rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл) rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл) rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл) rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл) rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл) rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл) rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл) rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл) rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл) rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл) прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В) rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл) rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл) rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл) rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл) rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл) rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл) rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл) rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл) rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В) rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В) rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл) rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В) rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл) rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл) rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В) rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл) rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл) rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В) rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл) rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В) rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В) rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В) rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В) rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл) rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В) частица:нет{}, // В этом нет сомнения. частица:нету{}, // В этом нету сомнения. rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов. прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В) rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В) rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В) rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В) rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл) rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В) rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в) rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В) rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В) rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В) rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В) rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В) rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В) rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В) rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В) rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В) rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В) rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В) rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В) rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В) rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:РАСКЛАДЫВАТЬСЯ{}, rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В) rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В) rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В) rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В) rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл) rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В) rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В) инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В) глагол:НАПИСАТЬ{ aux stress="напис^ать" }, прилагательное:НАПИСАННЫЙ{}, rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В) rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В) rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В) rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В) rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В) rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В) rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл) rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл) rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В) безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в) rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В) rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В) rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В) rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В) rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В) rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В) rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В) rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В) rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В) rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В) rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В) rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В) rus_verbs:объявить{}, // В газете объявили о конкурсе. rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В) rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В) rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в) rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в) rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в) rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в) инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В) глагол:ПАРИТЬ{ aux stress="пар^ить"}, деепричастие:паря{ aux stress="пар^я" }, прилагательное:ПАРЯЩИЙ{}, прилагательное:ПАРИВШИЙ{}, rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В) rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В) rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в) rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В) rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В) rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В) rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В) rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В) rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В) rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в) rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в) rus_verbs:принять{}, // Документ принят в следующей редакции (принять в) rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в) rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В) rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в) rus_verbs:звучать{}, // в доме звучала музыка (звучать в) rus_verbs:колебаться{}, // колеблется в выборе (колебаться в) rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в) rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в) rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в) rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в) rus_verbs:вычитывать{}, // вычитывать в книге rus_verbs:гудеть{}, // У него в ушах гудит. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки. rus_verbs:разойтись{}, // Они разошлись в темноте. rus_verbs:прибежать{}, // Мальчик прибежал в слезах. rus_verbs:биться{}, // Она билась в истерике. rus_verbs:регистрироваться{}, // регистрироваться в системе rus_verbs:считать{}, // я буду считать в уме rus_verbs:трахаться{}, // трахаться в гамаке rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке rus_verbs:разрушать{}, // разрушать в дробилке rus_verbs:засидеться{}, // засидеться в гостях rus_verbs:засиживаться{}, // засиживаться в гостях rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке) rus_verbs:навестить{}, // навестить в доме престарелых rus_verbs:запомнить{}, // запомнить в кэше rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.) rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка) rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику. rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.) rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу rus_verbs:оглядываться{}, // оглядываться в зеркале rus_verbs:нарисовать{}, // нарисовать в тетрадке rus_verbs:пробить{}, // пробить отверствие в стене rus_verbs:повертеть{}, // повертеть в руке rus_verbs:вертеть{}, // Я вертел в руках rus_verbs:рваться{}, // Веревка рвется в месте надреза rus_verbs:распространяться{}, // распространяться в среде наркоманов rus_verbs:попрощаться{}, // попрощаться в здании морга rus_verbs:соображать{}, // соображать в уме инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот) rus_verbs:разобрать{}, // разобрать в гараже rus_verbs:помереть{}, // помереть в пути rus_verbs:различить{}, // различить в темноте rus_verbs:рисовать{}, // рисовать в графическом редакторе rus_verbs:проследить{}, // проследить в записях камер слежения rus_verbs:совершаться{}, // Правосудие совершается в суде rus_verbs:задремать{}, // задремать в кровати rus_verbs:ругаться{}, // ругаться в комнате rus_verbs:зазвучать{}, // зазвучать в радиоприемниках rus_verbs:задохнуться{}, // задохнуться в воде rus_verbs:порождать{}, // порождать в неокрепших умах rus_verbs:отдыхать{}, // отдыхать в санатории rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении rus_verbs:образовать{}, // образовать в пробирке темную взвесь rus_verbs:отмечать{}, // отмечать в списке rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте rus_verbs:плясать{}, // плясать в откружении незнакомых людей rus_verbs:повысить{}, // повысить в звании rus_verbs:поджидать{}, // поджидать в подъезде rus_verbs:отказать{}, // отказать в пересмотре дела rus_verbs:раствориться{}, // раствориться в бензине rus_verbs:отражать{}, // отражать в стихах rus_verbs:дремать{}, // дремать в гамаке rus_verbs:применяться{}, // применяться в домашних условиях rus_verbs:присниться{}, // присниться во сне rus_verbs:трястись{}, // трястись в драндулете rus_verbs:сохранять{}, // сохранять в неприкосновенности rus_verbs:расстрелять{}, // расстрелять в ложбине rus_verbs:рассчитать{}, // рассчитать в программе rus_verbs:перебирать{}, // перебирать в руке rus_verbs:разбиться{}, // разбиться в аварии rus_verbs:поискать{}, // поискать в углу rus_verbs:мучиться{}, // мучиться в тесной клетке rus_verbs:замелькать{}, // замелькать в телевизоре rus_verbs:грустить{}, // грустить в одиночестве rus_verbs:крутить{}, // крутить в банке rus_verbs:объявиться{}, // объявиться в городе rus_verbs:подготовить{}, // подготовить в тайне rus_verbs:различать{}, // различать в смеси rus_verbs:обнаруживать{}, // обнаруживать в крови rus_verbs:киснуть{}, // киснуть в захолустье rus_verbs:оборваться{}, // оборваться в начале фразы rus_verbs:запутаться{}, // запутаться в веревках rus_verbs:общаться{}, // общаться в интимной обстановке rus_verbs:сочинить{}, // сочинить в ресторане rus_verbs:изобрести{}, // изобрести в домашней лаборатории rus_verbs:прокомментировать{}, // прокомментировать в своем блоге rus_verbs:давить{}, // давить в зародыше rus_verbs:повториться{}, // повториться в новом обличье rus_verbs:отставать{}, // отставать в общем зачете rus_verbs:разработать{}, // разработать в лаборатории rus_verbs:качать{}, // качать в кроватке rus_verbs:заменить{}, // заменить в двигателе rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере rus_verbs:забегать{}, // забегать в спешке rus_verbs:наделать{}, // наделать в решении ошибок rus_verbs:исказиться{}, // исказиться в кривом зеркале rus_verbs:тушить{}, // тушить в помещении пожар rus_verbs:охранять{}, // охранять в здании входы rus_verbs:приметить{}, // приметить в кустах rus_verbs:скрыть{}, // скрыть в складках одежды rus_verbs:удерживать{}, // удерживать в заложниках rus_verbs:увеличиваться{}, // увеличиваться в размере rus_verbs:красоваться{}, // красоваться в новом платье rus_verbs:сохраниться{}, // сохраниться в тепле rus_verbs:лечить{}, // лечить в стационаре rus_verbs:смешаться{}, // смешаться в баке rus_verbs:прокатиться{}, // прокатиться в троллейбусе rus_verbs:договариваться{}, // договариваться в закрытом кабинете rus_verbs:опубликовать{}, // опубликовать в официальном блоге rus_verbs:охотиться{}, // охотиться в прериях rus_verbs:отражаться{}, // отражаться в окне rus_verbs:понизить{}, // понизить в должности rus_verbs:обедать{}, // обедать в ресторане rus_verbs:посидеть{}, // посидеть в тени rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете rus_verbs:свершиться{}, // свершиться в суде rus_verbs:ночевать{}, // ночевать в гостинице rus_verbs:темнеть{}, // темнеть в воде rus_verbs:гибнуть{}, // гибнуть в застенках rus_verbs:усиливаться{}, // усиливаться в направлении главного удара rus_verbs:расплыться{}, // расплыться в улыбке rus_verbs:превышать{}, // превышать в несколько раз rus_verbs:проживать{}, // проживать в отдельной коморке rus_verbs:голубеть{}, // голубеть в тепле rus_verbs:исследовать{}, // исследовать в естественных условиях rus_verbs:обитать{}, // обитать в лесу rus_verbs:скучать{}, // скучать в одиночестве rus_verbs:сталкиваться{}, // сталкиваться в воздухе rus_verbs:таиться{}, // таиться в глубине rus_verbs:спасать{}, // спасать в море rus_verbs:заблудиться{}, // заблудиться в лесу rus_verbs:создаться{}, // создаться в новом виде rus_verbs:пошарить{}, // пошарить в кармане rus_verbs:планировать{}, // планировать в программе rus_verbs:отбить{}, // отбить в нижней части rus_verbs:отрицать{}, // отрицать в суде свою вину rus_verbs:основать{}, // основать в пустыне новый город rus_verbs:двоить{}, // двоить в глазах rus_verbs:устоять{}, // устоять в лодке rus_verbs:унять{}, // унять в ногах дрожь rus_verbs:отзываться{}, // отзываться в обзоре rus_verbs:притормозить{}, // притормозить в траве rus_verbs:читаться{}, // читаться в глазах rus_verbs:житься{}, // житься в деревне rus_verbs:заиграть{}, // заиграть в жилах rus_verbs:шевелить{}, // шевелить в воде rus_verbs:зазвенеть{}, // зазвенеть в ушах rus_verbs:зависнуть{}, // зависнуть в библиотеке rus_verbs:затаить{}, // затаить в душе обиду rus_verbs:сознаться{}, // сознаться в совершении rus_verbs:протекать{}, // протекать в легкой форме rus_verbs:выясняться{}, // выясняться в ходе эксперимента rus_verbs:скрестить{}, // скрестить в неволе rus_verbs:наводить{}, // наводить в комнате порядок rus_verbs:значиться{}, // значиться в документах rus_verbs:заинтересовать{}, // заинтересовать в получении результатов rus_verbs:познакомить{}, // познакомить в непринужденной обстановке rus_verbs:рассеяться{}, // рассеяться в воздухе rus_verbs:грохнуть{}, // грохнуть в подвале rus_verbs:обвинять{}, // обвинять в вымогательстве rus_verbs:столпиться{}, // столпиться в фойе rus_verbs:порыться{}, // порыться в сумке rus_verbs:ослабить{}, // ослабить в верхней части rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки rus_verbs:спастись{}, // спастись в хижине rus_verbs:прерваться{}, // прерваться в середине фразы rus_verbs:применять{}, // применять в повседневной работе rus_verbs:строиться{}, // строиться в зоне отчуждения rus_verbs:путешествовать{}, // путешествовать в самолете rus_verbs:побеждать{}, // побеждать в честной битве rus_verbs:погубить{}, // погубить в себе артиста rus_verbs:рассматриваться{}, // рассматриваться в следующей главе rus_verbs:продаваться{}, // продаваться в специализированном магазине rus_verbs:разместиться{}, // разместиться в аудитории rus_verbs:повидать{}, // повидать в жизни rus_verbs:настигнуть{}, // настигнуть в пригородах rus_verbs:сгрудиться{}, // сгрудиться в центре загона rus_verbs:укрыться{}, // укрыться в доме rus_verbs:расплакаться{}, // расплакаться в суде rus_verbs:пролежать{}, // пролежать в канаве rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде rus_verbs:поскользнуться{}, // поскользнуться в коридоре rus_verbs:таскать{}, // таскать в руках rus_verbs:нападать{}, // нападать в вольере rus_verbs:просматривать{}, // просматривать в браузере rus_verbs:обдумать{}, // обдумать в дороге rus_verbs:обвинить{}, // обвинить в измене rus_verbs:останавливать{}, // останавливать в дверях rus_verbs:теряться{}, // теряться в догадках rus_verbs:погибать{}, // погибать в бою rus_verbs:обозначать{}, // обозначать в списке rus_verbs:запрещать{}, // запрещать в парке rus_verbs:долететь{}, // долететь в вертолёте rus_verbs:тесниться{}, // тесниться в каморке rus_verbs:уменьшаться{}, // уменьшаться в размере rus_verbs:издавать{}, // издавать в небольшом издательстве rus_verbs:хоронить{}, // хоронить в море rus_verbs:перемениться{}, // перемениться в лице rus_verbs:установиться{}, // установиться в северных областях rus_verbs:прикидывать{}, // прикидывать в уме rus_verbs:затаиться{}, // затаиться в траве rus_verbs:раздобыть{}, // раздобыть в аптеке rus_verbs:перебросить{}, // перебросить в товарном составе rus_verbs:погружаться{}, // погружаться в батискафе rus_verbs:поживать{}, // поживать в одиночестве rus_verbs:признаваться{}, // признаваться в любви rus_verbs:захватывать{}, // захватывать в здании rus_verbs:покачиваться{}, // покачиваться в лодке rus_verbs:крутиться{}, // крутиться в колесе rus_verbs:помещаться{}, // помещаться в ящике rus_verbs:питаться{}, // питаться в столовой rus_verbs:отдохнуть{}, // отдохнуть в пансионате rus_verbs:кататься{}, // кататься в коляске rus_verbs:поработать{}, // поработать в цеху rus_verbs:подразумевать{}, // подразумевать в задании rus_verbs:ограбить{}, // ограбить в подворотне rus_verbs:преуспеть{}, // преуспеть в бизнесе rus_verbs:заерзать{}, // заерзать в кресле rus_verbs:разъяснить{}, // разъяснить в другой статье rus_verbs:продвинуться{}, // продвинуться в изучении rus_verbs:поколебаться{}, // поколебаться в начале rus_verbs:засомневаться{}, // засомневаться в честности rus_verbs:приникнуть{}, // приникнуть в уме rus_verbs:скривить{}, // скривить в усмешке rus_verbs:рассечь{}, // рассечь в центре опухоли rus_verbs:перепутать{}, // перепутать в роддоме rus_verbs:посмеяться{}, // посмеяться в перерыве rus_verbs:отмечаться{}, // отмечаться в полицейском участке rus_verbs:накопиться{}, // накопиться в отстойнике rus_verbs:уносить{}, // уносить в руках rus_verbs:навещать{}, // навещать в больнице rus_verbs:остыть{}, // остыть в проточной воде rus_verbs:запереться{}, // запереться в комнате rus_verbs:обогнать{}, // обогнать в первом круге rus_verbs:убеждаться{}, // убеждаться в неизбежности rus_verbs:подбирать{}, // подбирать в магазине rus_verbs:уничтожать{}, // уничтожать в полете rus_verbs:путаться{}, // путаться в показаниях rus_verbs:притаиться{}, // притаиться в темноте rus_verbs:проплывать{}, // проплывать в лодке rus_verbs:засесть{}, // засесть в окопе rus_verbs:подцепить{}, // подцепить в баре rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок rus_verbs:оправдаться{}, // оправдаться в суде rus_verbs:созреть{}, // созреть в естественных условиях rus_verbs:раскрываться{}, // раскрываться в подходящих условиях rus_verbs:ожидаться{}, // ожидаться в верхней части rus_verbs:одеваться{}, // одеваться в дорогих бутиках rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта rus_verbs:грабить{}, // грабить в подворотне rus_verbs:ужинать{}, // ужинать в ресторане rus_verbs:гонять{}, // гонять в жилах rus_verbs:уверить{}, // уверить в безопасности rus_verbs:потеряться{}, // потеряться в лесу rus_verbs:устанавливаться{}, // устанавливаться в комнате rus_verbs:предоставлять{}, // предоставлять в суде rus_verbs:протянуться{}, // протянуться в стене rus_verbs:допрашивать{}, // допрашивать в бункере rus_verbs:проработать{}, // проработать в кабинете rus_verbs:сосредоточить{}, // сосредоточить в своих руках rus_verbs:утвердить{}, // утвердить в должности rus_verbs:сочинять{}, // сочинять в дороге rus_verbs:померкнуть{}, // померкнуть в глазах rus_verbs:показываться{}, // показываться в окошке rus_verbs:похудеть{}, // похудеть в талии rus_verbs:проделывать{}, // проделывать в стене rus_verbs:прославиться{}, // прославиться в интернете rus_verbs:сдохнуть{}, // сдохнуть в нищете rus_verbs:раскинуться{}, // раскинуться в степи rus_verbs:развить{}, // развить в себе способности rus_verbs:уставать{}, // уставать в цеху rus_verbs:укрепить{}, // укрепить в земле rus_verbs:числиться{}, // числиться в списке rus_verbs:образовывать{}, // образовывать в смеси rus_verbs:екнуть{}, // екнуть в груди rus_verbs:одобрять{}, // одобрять в своей речи rus_verbs:запить{}, // запить в одиночестве rus_verbs:забыться{}, // забыться в тяжелом сне rus_verbs:чернеть{}, // чернеть в кислой среде rus_verbs:размещаться{}, // размещаться в гараже rus_verbs:соорудить{}, // соорудить в гараже rus_verbs:развивать{}, // развивать в себе rus_verbs:пастись{}, // пастись в пойме rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы rus_verbs:ослабнуть{}, // ослабнуть в сочленении rus_verbs:таить{}, // таить в себе инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке rus_verbs:приостановиться{}, // приостановиться в конце rus_verbs:топтаться{}, // топтаться в грязи rus_verbs:громить{}, // громить в финале rus_verbs:заменять{}, // заменять в основном составе rus_verbs:подъезжать{}, // подъезжать в колясках rus_verbs:вычислить{}, // вычислить в уме rus_verbs:заказывать{}, // заказывать в магазине rus_verbs:осуществить{}, // осуществить в реальных условиях rus_verbs:обосноваться{}, // обосноваться в дупле rus_verbs:пытать{}, // пытать в камере rus_verbs:поменять{}, // поменять в магазине rus_verbs:совершиться{}, // совершиться в суде rus_verbs:пролетать{}, // пролетать в вертолете rus_verbs:сбыться{}, // сбыться во сне rus_verbs:разговориться{}, // разговориться в отделении rus_verbs:преподнести{}, // преподнести в красивой упаковке rus_verbs:напечатать{}, // напечатать в типографии rus_verbs:прорвать{}, // прорвать в центре rus_verbs:раскачиваться{}, // раскачиваться в кресле rus_verbs:задерживаться{}, // задерживаться в дверях rus_verbs:угощать{}, // угощать в кафе rus_verbs:проступать{}, // проступать в глубине rus_verbs:шарить{}, // шарить в математике rus_verbs:увеличивать{}, // увеличивать в конце rus_verbs:расцвести{}, // расцвести в оранжерее rus_verbs:закипеть{}, // закипеть в баке rus_verbs:подлететь{}, // подлететь в вертолете rus_verbs:рыться{}, // рыться в куче rus_verbs:пожить{}, // пожить в гостинице rus_verbs:добираться{}, // добираться в попутном транспорте rus_verbs:перекрыть{}, // перекрыть в коридоре rus_verbs:продержаться{}, // продержаться в барокамере rus_verbs:разыскивать{}, // разыскивать в толпе rus_verbs:освобождать{}, // освобождать в зале суда rus_verbs:подметить{}, // подметить в человеке rus_verbs:передвигаться{}, // передвигаться в узкой юбке rus_verbs:продумать{}, // продумать в уме rus_verbs:извиваться{}, // извиваться в траве rus_verbs:процитировать{}, // процитировать в статье rus_verbs:прогуливаться{}, // прогуливаться в парке rus_verbs:защемить{}, // защемить в двери rus_verbs:увеличиться{}, // увеличиться в объеме rus_verbs:проявиться{}, // проявиться в результатах rus_verbs:заскользить{}, // заскользить в ботинках rus_verbs:пересказать{}, // пересказать в своем выступлении rus_verbs:протестовать{}, // протестовать в здании парламента rus_verbs:указываться{}, // указываться в путеводителе rus_verbs:копошиться{}, // копошиться в песке rus_verbs:проигнорировать{}, // проигнорировать в своей работе rus_verbs:купаться{}, // купаться в речке rus_verbs:подсчитать{}, // подсчитать в уме rus_verbs:разволноваться{}, // разволноваться в классе rus_verbs:придумывать{}, // придумывать в своем воображении rus_verbs:предусмотреть{}, // предусмотреть в программе rus_verbs:завертеться{}, // завертеться в колесе rus_verbs:зачерпнуть{}, // зачерпнуть в ручье rus_verbs:очистить{}, // очистить в химической лаборатории rus_verbs:прозвенеть{}, // прозвенеть в коридорах rus_verbs:уменьшиться{}, // уменьшиться в размере rus_verbs:колыхаться{}, // колыхаться в проточной воде rus_verbs:ознакомиться{}, // ознакомиться в автобусе rus_verbs:ржать{}, // ржать в аудитории rus_verbs:раскинуть{}, // раскинуть в микрорайоне rus_verbs:разлиться{}, // разлиться в воде rus_verbs:сквозить{}, // сквозить в словах rus_verbs:задушить{}, // задушить в объятиях rus_verbs:осудить{}, // осудить в особом порядке rus_verbs:разгромить{}, // разгромить в честном поединке rus_verbs:подслушать{}, // подслушать в кулуарах rus_verbs:проповедовать{}, // проповедовать в сельских районах rus_verbs:озарить{}, // озарить во сне rus_verbs:потирать{}, // потирать в предвкушении rus_verbs:описываться{}, // описываться в статье rus_verbs:качаться{}, // качаться в кроватке rus_verbs:усилить{}, // усилить в центре rus_verbs:прохаживаться{}, // прохаживаться в новом костюме rus_verbs:полечить{}, // полечить в больничке rus_verbs:сниматься{}, // сниматься в римейке rus_verbs:сыскать{}, // сыскать в наших краях rus_verbs:поприветствовать{}, // поприветствовать в коридоре rus_verbs:подтвердиться{}, // подтвердиться в эксперименте rus_verbs:плескаться{}, // плескаться в теплой водичке rus_verbs:расширяться{}, // расширяться в первом сегменте rus_verbs:мерещиться{}, // мерещиться в тумане rus_verbs:сгущаться{}, // сгущаться в воздухе rus_verbs:храпеть{}, // храпеть во сне rus_verbs:подержать{}, // подержать в руках rus_verbs:накинуться{}, // накинуться в подворотне rus_verbs:планироваться{}, // планироваться в закрытом режиме rus_verbs:пробудить{}, // пробудить в себе rus_verbs:побриться{}, // побриться в ванной rus_verbs:сгинуть{}, // сгинуть в пучине rus_verbs:окрестить{}, // окрестить в церкви инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления rus_verbs:замкнуться{}, // замкнуться в себе rus_verbs:прибавлять{}, // прибавлять в весе rus_verbs:проплыть{}, // проплыть в лодке rus_verbs:растворяться{}, // растворяться в тумане rus_verbs:упрекать{}, // упрекать в небрежности rus_verbs:затеряться{}, // затеряться в лабиринте rus_verbs:перечитывать{}, // перечитывать в поезде rus_verbs:перелететь{}, // перелететь в вертолете rus_verbs:оживать{}, // оживать в теплой воде rus_verbs:заглохнуть{}, // заглохнуть в полете rus_verbs:кольнуть{}, // кольнуть в боку rus_verbs:копаться{}, // копаться в куче rus_verbs:развлекаться{}, // развлекаться в клубе rus_verbs:отливать{}, // отливать в кустах rus_verbs:зажить{}, // зажить в деревне rus_verbs:одолжить{}, // одолжить в соседнем кабинете rus_verbs:заклинать{}, // заклинать в своей речи rus_verbs:различаться{}, // различаться в мелочах rus_verbs:печататься{}, // печататься в типографии rus_verbs:угадываться{}, // угадываться в контурах rus_verbs:обрывать{}, // обрывать в начале rus_verbs:поглаживать{}, // поглаживать в кармане rus_verbs:подписывать{}, // подписывать в присутствии понятых rus_verbs:добывать{}, // добывать в разломе rus_verbs:скопиться{}, // скопиться в воротах rus_verbs:повстречать{}, // повстречать в бане rus_verbs:совпасть{}, // совпасть в упрощенном виде rus_verbs:разрываться{}, // разрываться в точке спайки rus_verbs:улавливать{}, // улавливать в датчике rus_verbs:повстречаться{}, // повстречаться в лифте rus_verbs:отразить{}, // отразить в отчете rus_verbs:пояснять{}, // пояснять в примечаниях rus_verbs:накормить{}, // накормить в столовке rus_verbs:поужинать{}, // поужинать в ресторане инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить в молоке rus_verbs:освоить{}, // освоить в работе rus_verbs:зародиться{}, // зародиться в голове rus_verbs:отплыть{}, // отплыть в старой лодке rus_verbs:отстаивать{}, // отстаивать в суде rus_verbs:осуждать{}, // осуждать в своем выступлении rus_verbs:переговорить{}, // переговорить в перерыве rus_verbs:разгораться{}, // разгораться в сердце rus_verbs:укрыть{}, // укрыть в шалаше rus_verbs:томиться{}, // томиться в застенках rus_verbs:клубиться{}, // клубиться в воздухе rus_verbs:сжигать{}, // сжигать в топке rus_verbs:позавтракать{}, // позавтракать в кафешке rus_verbs:функционировать{}, // функционировать в лабораторных условиях rus_verbs:смять{}, // смять в руке rus_verbs:разместить{}, // разместить в интернете rus_verbs:пронести{}, // пронести в потайном кармане rus_verbs:руководствоваться{}, // руководствоваться в работе rus_verbs:нашарить{}, // нашарить в потемках rus_verbs:закрутить{}, // закрутить в вихре rus_verbs:просматриваться{}, // просматриваться в дальней перспективе rus_verbs:распознать{}, // распознать в незнакомце rus_verbs:повеситься{}, // повеситься в камере rus_verbs:обшарить{}, // обшарить в поисках наркотиков rus_verbs:наполняться{}, // наполняется в карьере rus_verbs:засвистеть{}, // засвистеть в воздухе rus_verbs:процветать{}, // процветать в мягком климате rus_verbs:шуршать{}, // шуршать в простенке rus_verbs:подхватывать{}, // подхватывать в полете инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе прилагательное:роившийся{}, прилагательное:роящийся{}, // деепричастие:роясь{ aux stress="ро^ясь" }, rus_verbs:преобладать{}, // преобладать в тексте rus_verbs:посветлеть{}, // посветлеть в лице rus_verbs:игнорировать{}, // игнорировать в рекомендациях rus_verbs:обсуждаться{}, // обсуждаться в кулуарах rus_verbs:отказывать{}, // отказывать в визе rus_verbs:ощупывать{}, // ощупывать в кармане rus_verbs:разливаться{}, // разливаться в цеху rus_verbs:расписаться{}, // расписаться в получении rus_verbs:учинить{}, // учинить в казарме rus_verbs:плестись{}, // плестись в хвосте rus_verbs:объявляться{}, // объявляться в группе rus_verbs:повышаться{}, // повышаться в первой части rus_verbs:напрягать{}, // напрягать в паху rus_verbs:разрабатывать{}, // разрабатывать в студии rus_verbs:хлопотать{}, // хлопотать в мэрии rus_verbs:прерывать{}, // прерывать в самом начале rus_verbs:каяться{}, // каяться в грехах rus_verbs:освоиться{}, // освоиться в кабине rus_verbs:подплыть{}, // подплыть в лодке rus_verbs:замигать{}, // замигать в темноте rus_verbs:оскорблять{}, // оскорблять в выступлении rus_verbs:торжествовать{}, // торжествовать в душе rus_verbs:поправлять{}, // поправлять в прологе rus_verbs:угадывать{}, // угадывать в размытом изображении rus_verbs:потоптаться{}, // потоптаться в прихожей rus_verbs:переправиться{}, // переправиться в лодочке rus_verbs:увериться{}, // увериться в невиновности rus_verbs:забрезжить{}, // забрезжить в конце тоннеля rus_verbs:утвердиться{}, // утвердиться во мнении rus_verbs:завывать{}, // завывать в трубе rus_verbs:заварить{}, // заварить в заварнике rus_verbs:скомкать{}, // скомкать в руке rus_verbs:перемещаться{}, // перемещаться в капсуле инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле rus_verbs:праздновать{}, // праздновать в баре rus_verbs:мигать{}, // мигать в темноте rus_verbs:обучить{}, // обучить в мастерской rus_verbs:орудовать{}, // орудовать в кладовке rus_verbs:упорствовать{}, // упорствовать в заблуждении rus_verbs:переминаться{}, // переминаться в прихожей rus_verbs:подрасти{}, // подрасти в теплице rus_verbs:предписываться{}, // предписываться в законе rus_verbs:приписать{}, // приписать в конце rus_verbs:задаваться{}, // задаваться в своей статье rus_verbs:чинить{}, // чинить в домашних условиях rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке rus_verbs:пообедать{}, // пообедать в ресторанчике rus_verbs:жрать{}, // жрать в чуланчике rus_verbs:исполняться{}, // исполняться в антракте rus_verbs:гнить{}, // гнить в тюрьме rus_verbs:глодать{}, // глодать в конуре rus_verbs:прослушать{}, // прослушать в дороге rus_verbs:истратить{}, // истратить в кабаке rus_verbs:стареть{}, // стареть в одиночестве rus_verbs:разжечь{}, // разжечь в сердце rus_verbs:совещаться{}, // совещаться в кабинете rus_verbs:покачивать{}, // покачивать в кроватке rus_verbs:отсидеть{}, // отсидеть в одиночке rus_verbs:формировать{}, // формировать в умах rus_verbs:захрапеть{}, // захрапеть во сне rus_verbs:петься{}, // петься в хоре rus_verbs:объехать{}, // объехать в автобусе rus_verbs:поселить{}, // поселить в гостинице rus_verbs:предаться{}, // предаться в книге rus_verbs:заворочаться{}, // заворочаться во сне rus_verbs:напрятать{}, // напрятать в карманах rus_verbs:очухаться{}, // очухаться в незнакомом месте rus_verbs:ограничивать{}, // ограничивать в движениях rus_verbs:завертеть{}, // завертеть в руках rus_verbs:печатать{}, // печатать в редакторе rus_verbs:теплиться{}, // теплиться в сердце rus_verbs:увязнуть{}, // увязнуть в зыбучем песке rus_verbs:усмотреть{}, // усмотреть в обращении rus_verbs:отыскаться{}, // отыскаться в запасах rus_verbs:потушить{}, // потушить в горле огонь rus_verbs:поубавиться{}, // поубавиться в размере rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти rus_verbs:смыть{}, // смыть в ванной rus_verbs:заместить{}, // заместить в кресле rus_verbs:угасать{}, // угасать в одиночестве rus_verbs:сразить{}, // сразить в споре rus_verbs:фигурировать{}, // фигурировать в бюллетене rus_verbs:расплываться{}, // расплываться в глазах rus_verbs:сосчитать{}, // сосчитать в уме rus_verbs:сгуститься{}, // сгуститься в воздухе rus_verbs:цитировать{}, // цитировать в своей статье rus_verbs:помяться{}, // помяться в давке rus_verbs:затрагивать{}, // затрагивать в процессе выполнения rus_verbs:обтереть{}, // обтереть в гараже rus_verbs:подстрелить{}, // подстрелить в пойме реки rus_verbs:растереть{}, // растереть в руке rus_verbs:подавлять{}, // подавлять в зародыше rus_verbs:смешиваться{}, // смешиваться в чане инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке rus_verbs:сократиться{}, // сократиться в обхвате rus_verbs:занервничать{}, // занервничать в кабинете rus_verbs:соприкоснуться{}, // соприкоснуться в полете rus_verbs:обозначить{}, // обозначить в объявлении rus_verbs:обучаться{}, // обучаться в училище rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы rus_verbs:лелеять{}, // лелеять в сердце rus_verbs:поддерживаться{}, // поддерживаться в суде rus_verbs:уплыть{}, // уплыть в лодочке rus_verbs:резвиться{}, // резвиться в саду rus_verbs:поерзать{}, // поерзать в гамаке rus_verbs:оплатить{}, // оплатить в ресторане rus_verbs:похвастаться{}, // похвастаться в компании rus_verbs:знакомиться{}, // знакомиться в классе rus_verbs:приплыть{}, // приплыть в подводной лодке rus_verbs:зажигать{}, // зажигать в классе rus_verbs:смыслить{}, // смыслить в математике rus_verbs:закопать{}, // закопать в огороде rus_verbs:порхать{}, // порхать в зарослях rus_verbs:потонуть{}, // потонуть в бумажках rus_verbs:стирать{}, // стирать в холодной воде rus_verbs:подстерегать{}, // подстерегать в придорожных кустах rus_verbs:погулять{}, // погулять в парке rus_verbs:предвкушать{}, // предвкушать в воображении rus_verbs:ошеломить{}, // ошеломить в бою rus_verbs:удостовериться{}, // удостовериться в безопасности rus_verbs:огласить{}, // огласить в заключительной части rus_verbs:разбогатеть{}, // разбогатеть в деревне rus_verbs:грохотать{}, // грохотать в мастерской rus_verbs:реализоваться{}, // реализоваться в должности rus_verbs:красть{}, // красть в магазине rus_verbs:нарваться{}, // нарваться в коридоре rus_verbs:застывать{}, // застывать в неудобной позе rus_verbs:толкаться{}, // толкаться в тесной комнате rus_verbs:извлекать{}, // извлекать в аппарате rus_verbs:обжигать{}, // обжигать в печи rus_verbs:запечатлеть{}, // запечатлеть в кинохронике rus_verbs:тренироваться{}, // тренироваться в зале rus_verbs:поспорить{}, // поспорить в кабинете rus_verbs:рыскать{}, // рыскать в лесу rus_verbs:надрываться{}, // надрываться в шахте rus_verbs:сняться{}, // сняться в фильме rus_verbs:закружить{}, // закружить в танце rus_verbs:затонуть{}, // затонуть в порту rus_verbs:побыть{}, // побыть в гостях rus_verbs:почистить{}, // почистить в носу rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре rus_verbs:подслушивать{}, // подслушивать в классе rus_verbs:сгорать{}, // сгорать в танке rus_verbs:разочароваться{}, // разочароваться в артисте инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках rus_verbs:мять{}, // мять в руках rus_verbs:подраться{}, // подраться в классе rus_verbs:замести{}, // замести в прихожей rus_verbs:откладываться{}, // откладываться в печени rus_verbs:обозначаться{}, // обозначаться в перечне rus_verbs:просиживать{}, // просиживать в интернете rus_verbs:соприкасаться{}, // соприкасаться в точке rus_verbs:начертить{}, // начертить в тетрадке rus_verbs:уменьшать{}, // уменьшать в поперечнике rus_verbs:тормозить{}, // тормозить в облаке rus_verbs:затевать{}, // затевать в лаборатории rus_verbs:затопить{}, // затопить в бухте rus_verbs:задерживать{}, // задерживать в лифте rus_verbs:прогуляться{}, // прогуляться в лесу rus_verbs:прорубить{}, // прорубить во льду rus_verbs:очищать{}, // очищать в кислоте rus_verbs:полулежать{}, // полулежать в гамаке rus_verbs:исправить{}, // исправить в задании rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи rus_verbs:замучить{}, // замучить в плену rus_verbs:разрушаться{}, // разрушаться в верхней части rus_verbs:ерзать{}, // ерзать в кресле rus_verbs:покопаться{}, // покопаться в залежах rus_verbs:раскаяться{}, // раскаяться в содеянном rus_verbs:пробежаться{}, // пробежаться в парке rus_verbs:полежать{}, // полежать в гамаке rus_verbs:позаимствовать{}, // позаимствовать в книге rus_verbs:снижать{}, // снижать в несколько раз rus_verbs:черпать{}, // черпать в поэзии rus_verbs:заверять{}, // заверять в своей искренности rus_verbs:проглядеть{}, // проглядеть в сумерках rus_verbs:припарковать{}, // припарковать во дворе rus_verbs:сверлить{}, // сверлить в стене rus_verbs:здороваться{}, // здороваться в аудитории rus_verbs:рожать{}, // рожать в воде rus_verbs:нацарапать{}, // нацарапать в тетрадке rus_verbs:затопать{}, // затопать в коридоре rus_verbs:прописать{}, // прописать в правилах rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах rus_verbs:снизить{}, // снизить в несколько раз rus_verbs:заблуждаться{}, // заблуждаться в своей теории rus_verbs:откопать{}, // откопать в отвалах rus_verbs:смастерить{}, // смастерить в лаборатории rus_verbs:замедлиться{}, // замедлиться в парафине rus_verbs:избивать{}, // избивать в участке rus_verbs:мыться{}, // мыться в бане rus_verbs:сварить{}, // сварить в кастрюльке rus_verbs:раскопать{}, // раскопать в снегу rus_verbs:крепиться{}, // крепиться в держателе rus_verbs:дробить{}, // дробить в мельнице rus_verbs:попить{}, // попить в ресторанчике rus_verbs:затронуть{}, // затронуть в душе rus_verbs:лязгнуть{}, // лязгнуть в тишине rus_verbs:заправлять{}, // заправлять в полете rus_verbs:размножаться{}, // размножаться в неволе rus_verbs:потопить{}, // потопить в Тихом Океане rus_verbs:кушать{}, // кушать в столовой rus_verbs:замолкать{}, // замолкать в замешательстве rus_verbs:измеряться{}, // измеряться в дюймах rus_verbs:сбываться{}, // сбываться в мечтах rus_verbs:задернуть{}, // задернуть в комнате rus_verbs:затихать{}, // затихать в темноте rus_verbs:прослеживаться{}, // прослеживается в журнале rus_verbs:прерываться{}, // прерывается в начале rus_verbs:изображаться{}, // изображается в любых фильмах rus_verbs:фиксировать{}, // фиксировать в данной точке rus_verbs:ослаблять{}, // ослаблять в поясе rus_verbs:зреть{}, // зреть в теплице rus_verbs:зеленеть{}, // зеленеть в огороде rus_verbs:критиковать{}, // критиковать в статье rus_verbs:облететь{}, // облететь в частном вертолете rus_verbs:разбросать{}, // разбросать в комнате rus_verbs:заразиться{}, // заразиться в людном месте rus_verbs:рассеять{}, // рассеять в бою rus_verbs:печься{}, // печься в духовке rus_verbs:поспать{}, // поспать в палатке rus_verbs:заступиться{}, // заступиться в драке rus_verbs:сплетаться{}, // сплетаться в середине rus_verbs:поместиться{}, // поместиться в мешке rus_verbs:спереть{}, // спереть в лавке // инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде // инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш }, rus_verbs:проваляться{}, // проваляться в постели rus_verbs:лечиться{}, // лечиться в стационаре rus_verbs:определиться{}, // определиться в честном бою rus_verbs:обработать{}, // обработать в растворе rus_verbs:пробивать{}, // пробивать в стене rus_verbs:перемешаться{}, // перемешаться в чане rus_verbs:чесать{}, // чесать в паху rus_verbs:пролечь{}, // пролечь в пустынной местности rus_verbs:скитаться{}, // скитаться в дальних странах rus_verbs:затрудняться{}, // затрудняться в выборе rus_verbs:отряхнуться{}, // отряхнуться в коридоре rus_verbs:разыгрываться{}, // разыгрываться в лотерее rus_verbs:помолиться{}, // помолиться в церкви rus_verbs:предписывать{}, // предписывать в рецепте rus_verbs:порваться{}, // порваться в слабом месте rus_verbs:греться{}, // греться в здании rus_verbs:опровергать{}, // опровергать в своем выступлении rus_verbs:помянуть{}, // помянуть в своем выступлении rus_verbs:допросить{}, // допросить в прокуратуре rus_verbs:материализоваться{}, // материализоваться в соседнем здании rus_verbs:рассеиваться{}, // рассеиваться в воздухе rus_verbs:перевозить{}, // перевозить в вагоне rus_verbs:отбывать{}, // отбывать в тюрьме rus_verbs:попахивать{}, // попахивать в отхожем месте rus_verbs:перечислять{}, // перечислять в заключении rus_verbs:зарождаться{}, // зарождаться в дебрях rus_verbs:предъявлять{}, // предъявлять в своем письме rus_verbs:распространять{}, // распространять в сети rus_verbs:пировать{}, // пировать в соседнем селе rus_verbs:начертать{}, // начертать в летописи rus_verbs:расцветать{}, // расцветать в подходящих условиях rus_verbs:царствовать{}, // царствовать в южной части материка rus_verbs:накопить{}, // накопить в буфере rus_verbs:закрутиться{}, // закрутиться в рутине rus_verbs:отработать{}, // отработать в забое rus_verbs:обокрасть{}, // обокрасть в автобусе rus_verbs:прокладывать{}, // прокладывать в снегу rus_verbs:ковырять{}, // ковырять в носу rus_verbs:копить{}, // копить в очереди rus_verbs:полечь{}, // полечь в степях rus_verbs:щебетать{}, // щебетать в кустиках rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении rus_verbs:посеять{}, // посеять в огороде rus_verbs:разъезжать{}, // разъезжать в кабриолете rus_verbs:замечаться{}, // замечаться в лесу rus_verbs:просчитать{}, // просчитать в уме rus_verbs:маяться{}, // маяться в командировке rus_verbs:выхватывать{}, // выхватывать в тексте rus_verbs:креститься{}, // креститься в деревенской часовне rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты rus_verbs:настигать{}, // настигать в огороде rus_verbs:разгуливать{}, // разгуливать в роще rus_verbs:насиловать{}, // насиловать в квартире rus_verbs:побороть{}, // побороть в себе rus_verbs:учитывать{}, // учитывать в расчетах rus_verbs:искажать{}, // искажать в заметке rus_verbs:пропить{}, // пропить в кабаке rus_verbs:катать{}, // катать в лодочке rus_verbs:припрятать{}, // припрятать в кармашке rus_verbs:запаниковать{}, // запаниковать в бою rus_verbs:рассыпать{}, // рассыпать в траве rus_verbs:застревать{}, // застревать в ограде rus_verbs:зажигаться{}, // зажигаться в сумерках rus_verbs:жарить{}, // жарить в масле rus_verbs:накапливаться{}, // накапливаться в костях rus_verbs:распуститься{}, // распуститься в горшке rus_verbs:проголосовать{}, // проголосовать в передвижном пункте rus_verbs:странствовать{}, // странствовать в автомобиле rus_verbs:осматриваться{}, // осматриваться в хоромах rus_verbs:разворачивать{}, // разворачивать в спортзале rus_verbs:заскучать{}, // заскучать в самолете rus_verbs:напутать{}, // напутать в расчете rus_verbs:перекусить{}, // перекусить в столовой rus_verbs:спасаться{}, // спасаться в автономной капсуле rus_verbs:посовещаться{}, // посовещаться в комнате rus_verbs:доказываться{}, // доказываться в статье rus_verbs:познаваться{}, // познаваться в беде rus_verbs:загрустить{}, // загрустить в одиночестве rus_verbs:оживить{}, // оживить в памяти rus_verbs:переворачиваться{}, // переворачиваться в гробу rus_verbs:заприметить{}, // заприметить в лесу rus_verbs:отравиться{}, // отравиться в забегаловке rus_verbs:продержать{}, // продержать в клетке rus_verbs:выявить{}, // выявить в костях rus_verbs:заседать{}, // заседать в совете rus_verbs:расплачиваться{}, // расплачиваться в первой кассе rus_verbs:проломить{}, // проломить в двери rus_verbs:подражать{}, // подражать в мелочах rus_verbs:подсчитывать{}, // подсчитывать в уме rus_verbs:опережать{}, // опережать во всем rus_verbs:сформироваться{}, // сформироваться в облаке rus_verbs:укрепиться{}, // укрепиться в мнении rus_verbs:отстоять{}, // отстоять в очереди rus_verbs:развертываться{}, // развертываться в месте испытания rus_verbs:замерзать{}, // замерзать во льду rus_verbs:утопать{}, // утопать в снегу rus_verbs:раскаиваться{}, // раскаиваться в содеянном rus_verbs:организовывать{}, // организовывать в пионерлагере rus_verbs:перевестись{}, // перевестись в наших краях rus_verbs:смешивать{}, // смешивать в блендере rus_verbs:ютиться{}, // ютиться в тесной каморке rus_verbs:прождать{}, // прождать в аудитории rus_verbs:подыскивать{}, // подыскивать в женском общежитии rus_verbs:замочить{}, // замочить в сортире rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке rus_verbs:растирать{}, // растирать в ступке rus_verbs:замедлять{}, // замедлять в парафине rus_verbs:переспать{}, // переспать в палатке rus_verbs:рассекать{}, // рассекать в кабриолете rus_verbs:отыскивать{}, // отыскивать в залежах rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке rus_verbs:укрываться{}, // укрываться в землянке rus_verbs:запечься{}, // запечься в золе rus_verbs:догорать{}, // догорать в темноте rus_verbs:застилать{}, // застилать в коридоре rus_verbs:сыскаться{}, // сыскаться в деревне rus_verbs:переделать{}, // переделать в мастерской rus_verbs:разъяснять{}, // разъяснять в своей лекции rus_verbs:селиться{}, // селиться в центре rus_verbs:оплачивать{}, // оплачивать в магазине rus_verbs:переворачивать{}, // переворачивать в закрытой банке rus_verbs:упражняться{}, // упражняться в остроумии rus_verbs:пометить{}, // пометить в списке rus_verbs:припомниться{}, // припомниться в завещании rus_verbs:приютить{}, // приютить в амбаре rus_verbs:натерпеться{}, // натерпеться в темнице rus_verbs:затеваться{}, // затеваться в клубе rus_verbs:уплывать{}, // уплывать в лодке rus_verbs:скиснуть{}, // скиснуть в бидоне rus_verbs:заколоть{}, // заколоть в боку rus_verbs:замерцать{}, // замерцать в темноте rus_verbs:фиксироваться{}, // фиксироваться в протоколе rus_verbs:запираться{}, // запираться в комнате rus_verbs:съезжаться{}, // съезжаться в каретах rus_verbs:толочься{}, // толочься в ступе rus_verbs:потанцевать{}, // потанцевать в клубе rus_verbs:побродить{}, // побродить в парке rus_verbs:назревать{}, // назревать в коллективе rus_verbs:дохнуть{}, // дохнуть в питомнике rus_verbs:крестить{}, // крестить в деревенской церквушке rus_verbs:рассчитаться{}, // рассчитаться в банке rus_verbs:припарковаться{}, // припарковаться во дворе rus_verbs:отхватить{}, // отхватить в магазинчике rus_verbs:остывать{}, // остывать в холодильнике rus_verbs:составляться{}, // составляться в атмосфере тайны rus_verbs:переваривать{}, // переваривать в тишине rus_verbs:хвастать{}, // хвастать в казино rus_verbs:отрабатывать{}, // отрабатывать в теплице rus_verbs:разлечься{}, // разлечься в кровати rus_verbs:прокручивать{}, // прокручивать в голове rus_verbs:очертить{}, // очертить в воздухе rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей rus_verbs:выявлять{}, // выявлять в боевых условиях rus_verbs:караулить{}, // караулить в лифте rus_verbs:расставлять{}, // расставлять в бойницах rus_verbs:прокрутить{}, // прокрутить в голове rus_verbs:пересказывать{}, // пересказывать в первой главе rus_verbs:задавить{}, // задавить в зародыше rus_verbs:хозяйничать{}, // хозяйничать в холодильнике rus_verbs:хвалиться{}, // хвалиться в детском садике rus_verbs:оперировать{}, // оперировать в полевом госпитале rus_verbs:формулировать{}, // формулировать в следующей главе rus_verbs:застигнуть{}, // застигнуть в неприглядном виде rus_verbs:замурлыкать{}, // замурлыкать в тепле rus_verbs:поддакивать{}, // поддакивать в споре rus_verbs:прочертить{}, // прочертить в воздухе rus_verbs:отменять{}, // отменять в городе коменданский час rus_verbs:колдовать{}, // колдовать в лаборатории rus_verbs:отвозить{}, // отвозить в машине rus_verbs:трахать{}, // трахать в гамаке rus_verbs:повозиться{}, // повозиться в мешке rus_verbs:ремонтировать{}, // ремонтировать в центре rus_verbs:робеть{}, // робеть в гостях rus_verbs:перепробовать{}, // перепробовать в деле инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш }, rus_verbs:покаяться{}, // покаяться в церкви rus_verbs:попрыгать{}, // попрыгать в бассейне rus_verbs:умалчивать{}, // умалчивать в своем докладе rus_verbs:ковыряться{}, // ковыряться в старой технике rus_verbs:расписывать{}, // расписывать в деталях rus_verbs:вязнуть{}, // вязнуть в песке rus_verbs:погрязнуть{}, // погрязнуть в скандалах rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу rus_verbs:зажимать{}, // зажимать в углу rus_verbs:стискивать{}, // стискивать в ладонях rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса rus_verbs:израсходовать{}, // израсходовать в полете rus_verbs:клокотать{}, // клокотать в жерле rus_verbs:обвиняться{}, // обвиняться в растрате rus_verbs:уединиться{}, // уединиться в кладовке rus_verbs:подохнуть{}, // подохнуть в болоте rus_verbs:кипятиться{}, // кипятиться в чайнике rus_verbs:уродиться{}, // уродиться в лесу rus_verbs:продолжиться{}, // продолжиться в баре rus_verbs:расшифровать{}, // расшифровать в специальном устройстве rus_verbs:посапывать{}, // посапывать в кровати rus_verbs:скрючиться{}, // скрючиться в мешке rus_verbs:лютовать{}, // лютовать в отдаленных селах rus_verbs:расписать{}, // расписать в статье rus_verbs:публиковаться{}, // публиковаться в научном журнале rus_verbs:зарегистрировать{}, // зарегистрировать в комитете rus_verbs:прожечь{}, // прожечь в листе rus_verbs:переждать{}, // переждать в окопе rus_verbs:публиковать{}, // публиковать в журнале rus_verbs:морщить{}, // морщить в уголках глаз rus_verbs:спиться{}, // спиться в одиночестве rus_verbs:изведать{}, // изведать в гареме rus_verbs:обмануться{}, // обмануться в ожиданиях rus_verbs:сочетать{}, // сочетать в себе rus_verbs:подрабатывать{}, // подрабатывать в магазине rus_verbs:репетировать{}, // репетировать в студии rus_verbs:рябить{}, // рябить в глазах rus_verbs:намочить{}, // намочить в луже rus_verbs:скатать{}, // скатать в руке rus_verbs:одевать{}, // одевать в магазине rus_verbs:испечь{}, // испечь в духовке rus_verbs:сбрить{}, // сбрить в подмышках rus_verbs:зажужжать{}, // зажужжать в ухе rus_verbs:сберечь{}, // сберечь в тайном месте rus_verbs:согреться{}, // согреться в хижине инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш }, rus_verbs:переплыть{}, // переплыть в лодочке rus_verbs:передохнуть{}, // передохнуть в тени rus_verbs:отсвечивать{}, // отсвечивать в зеркалах rus_verbs:переправляться{}, // переправляться в лодках rus_verbs:накупить{}, // накупить в магазине rus_verbs:проторчать{}, // проторчать в очереди rus_verbs:проскальзывать{}, // проскальзывать в сообщениях rus_verbs:застукать{}, // застукать в солярии rus_verbs:наесть{}, // наесть в отпуске rus_verbs:подвизаться{}, // подвизаться в новом деле rus_verbs:вычистить{}, // вычистить в саду rus_verbs:кормиться{}, // кормиться в лесу rus_verbs:покурить{}, // покурить в саду rus_verbs:понизиться{}, // понизиться в ранге rus_verbs:зимовать{}, // зимовать в избушке rus_verbs:проверяться{}, // проверяться в службе безопасности rus_verbs:подпирать{}, // подпирать в первом забое rus_verbs:кувыркаться{}, // кувыркаться в постели rus_verbs:похрапывать{}, // похрапывать в постели rus_verbs:завязнуть{}, // завязнуть в песке rus_verbs:трактовать{}, // трактовать в исследовательской статье rus_verbs:замедляться{}, // замедляться в тяжелой воде rus_verbs:шастать{}, // шастать в здании rus_verbs:заночевать{}, // заночевать в пути rus_verbs:наметиться{}, // наметиться в исследованиях рака rus_verbs:освежить{}, // освежить в памяти rus_verbs:оспаривать{}, // оспаривать в суде rus_verbs:умещаться{}, // умещаться в ячейке rus_verbs:искупить{}, // искупить в бою rus_verbs:отсиживаться{}, // отсиживаться в тылу rus_verbs:мчать{}, // мчать в кабриолете rus_verbs:обличать{}, // обличать в своем выступлении rus_verbs:сгнить{}, // сгнить в тюряге rus_verbs:опробовать{}, // опробовать в деле rus_verbs:тренировать{}, // тренировать в зале rus_verbs:прославить{}, // прославить в академии rus_verbs:учитываться{}, // учитываться в дипломной работе rus_verbs:повеселиться{}, // повеселиться в лагере rus_verbs:поумнеть{}, // поумнеть в карцере rus_verbs:перестрелять{}, // перестрелять в воздухе rus_verbs:проведать{}, // проведать в больнице rus_verbs:измучиться{}, // измучиться в деревне rus_verbs:прощупать{}, // прощупать в глубине rus_verbs:изготовлять{}, // изготовлять в сарае rus_verbs:свирепствовать{}, // свирепствовать в популяции rus_verbs:иссякать{}, // иссякать в источнике rus_verbs:гнездиться{}, // гнездиться в дупле rus_verbs:разогнаться{}, // разогнаться в спортивной машине rus_verbs:опознавать{}, // опознавать в неизвестном rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках rus_verbs:редактировать{}, // редактировать в редакторе rus_verbs:покупаться{}, // покупаться в магазине rus_verbs:промышлять{}, // промышлять в роще rus_verbs:растягиваться{}, // растягиваться в коридоре rus_verbs:приобретаться{}, // приобретаться в антикварных лавках инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш }, rus_verbs:запечатлеться{}, // запечатлеться в мозгу rus_verbs:укрывать{}, // укрывать в подвале rus_verbs:закрепиться{}, // закрепиться в первой башне rus_verbs:освежать{}, // освежать в памяти rus_verbs:громыхать{}, // громыхать в ванной инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш }, rus_verbs:добываться{}, // добываться в шахтах rus_verbs:растворить{}, // растворить в кислоте rus_verbs:приплясывать{}, // приплясывать в гримерке rus_verbs:доживать{}, // доживать в доме престарелых rus_verbs:отпраздновать{}, // отпраздновать в ресторане rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях rus_verbs:помыть{}, // помыть в проточной воде инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш }, прилагательное:увязавший{ вид:несоверш }, rus_verbs:наличествовать{}, // наличествовать в запаснике rus_verbs:нащупывать{}, // нащупывать в кармане rus_verbs:повествоваться{}, // повествоваться в рассказе rus_verbs:отремонтировать{}, // отремонтировать в техцентре rus_verbs:покалывать{}, // покалывать в правом боку rus_verbs:сиживать{}, // сиживать в саду rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях rus_verbs:укрепляться{}, // укрепляться в мнении rus_verbs:разниться{}, // разниться во взглядах rus_verbs:сполоснуть{}, // сполоснуть в водичке rus_verbs:скупать{}, // скупать в магазине rus_verbs:почесывать{}, // почесывать в паху rus_verbs:оформлять{}, // оформлять в конторе rus_verbs:распускаться{}, // распускаться в садах rus_verbs:зарябить{}, // зарябить в глазах rus_verbs:загореть{}, // загореть в Испании rus_verbs:очищаться{}, // очищаться в баке rus_verbs:остудить{}, // остудить в холодной воде rus_verbs:разбомбить{}, // разбомбить в горах rus_verbs:издохнуть{}, // издохнуть в бедности rus_verbs:проехаться{}, // проехаться в новой машине rus_verbs:задействовать{}, // задействовать в анализе rus_verbs:произрастать{}, // произрастать в степи rus_verbs:разуться{}, // разуться в прихожей rus_verbs:сооружать{}, // сооружать в огороде rus_verbs:зачитывать{}, // зачитывать в суде rus_verbs:состязаться{}, // состязаться в остроумии rus_verbs:ополоснуть{}, // ополоснуть в молоке rus_verbs:уместиться{}, // уместиться в кармане rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом rus_verbs:стираться{}, // стираться в стиральной машине rus_verbs:искупаться{}, // искупаться в прохладной реке rus_verbs:курировать{}, // курировать в правительстве rus_verbs:закупить{}, // закупить в магазине rus_verbs:плодиться{}, // плодиться в подходящих условиях rus_verbs:горланить{}, // горланить в парке rus_verbs:першить{}, // першить в горле rus_verbs:пригрезиться{}, // пригрезиться во сне rus_verbs:исправлять{}, // исправлять в тетрадке rus_verbs:расслабляться{}, // расслабляться в гамаке rus_verbs:скапливаться{}, // скапливаться в нижней части rus_verbs:сплетничать{}, // сплетничают в комнате rus_verbs:раздевать{}, // раздевать в кабинке rus_verbs:окопаться{}, // окопаться в лесу rus_verbs:загорать{}, // загорать в Испании rus_verbs:подпевать{}, // подпевать в церковном хоре rus_verbs:прожужжать{}, // прожужжать в динамике rus_verbs:изучаться{}, // изучаться в дикой природе rus_verbs:заклубиться{}, // заклубиться в воздухе rus_verbs:подметать{}, // подметать в зале rus_verbs:подозреваться{}, // подозреваться в совершении кражи rus_verbs:обогащать{}, // обогащать в специальном аппарате rus_verbs:издаться{}, // издаться в другом издательстве rus_verbs:справить{}, // справить в кустах нужду rus_verbs:помыться{}, // помыться в бане rus_verbs:проскакивать{}, // проскакивать в словах rus_verbs:попивать{}, // попивать в кафе чай rus_verbs:оформляться{}, // оформляться в регистратуре rus_verbs:чирикать{}, // чирикать в кустах rus_verbs:скупить{}, // скупить в магазинах rus_verbs:переночевать{}, // переночевать в гостинице rus_verbs:концентрироваться{}, // концентрироваться в пробирке rus_verbs:одичать{}, // одичать в лесу rus_verbs:ковырнуть{}, // ковырнуть в ухе rus_verbs:затеплиться{}, // затеплиться в глубине души rus_verbs:разгрести{}, // разгрести в задачах залежи rus_verbs:застопориться{}, // застопориться в начале списка rus_verbs:перечисляться{}, // перечисляться во введении rus_verbs:покататься{}, // покататься в парке аттракционов rus_verbs:изловить{}, // изловить в поле rus_verbs:прославлять{}, // прославлять в стихах rus_verbs:промочить{}, // промочить в луже rus_verbs:поделывать{}, // поделывать в отпуске rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии rus_verbs:подстеречь{}, // подстеречь в подъезде rus_verbs:прикупить{}, // прикупить в магазине rus_verbs:перемешивать{}, // перемешивать в кастрюле rus_verbs:тискать{}, // тискать в углу rus_verbs:купать{}, // купать в теплой водичке rus_verbs:завариться{}, // завариться в стакане rus_verbs:притулиться{}, // притулиться в углу rus_verbs:пострелять{}, // пострелять в тире rus_verbs:навесить{}, // навесить в больнице инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш }, rus_verbs:нежиться{}, // нежится в постельке rus_verbs:притомиться{}, // притомиться в школе rus_verbs:раздвоиться{}, // раздвоиться в глазах rus_verbs:навалить{}, // навалить в углу rus_verbs:замуровать{}, // замуровать в склепе rus_verbs:поселяться{}, // поселяться в кроне дуба rus_verbs:потягиваться{}, // потягиваться в кровати rus_verbs:укачать{}, // укачать в поезде rus_verbs:отлеживаться{}, // отлеживаться в гамаке rus_verbs:разменять{}, // разменять в кассе rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде rus_verbs:ржаветь{}, // ржаветь в воде rus_verbs:уличить{}, // уличить в плагиате rus_verbs:мутиться{}, // мутиться в голове rus_verbs:растворять{}, // растворять в бензоле rus_verbs:двоиться{}, // двоиться в глазах rus_verbs:оговорить{}, // оговорить в договоре rus_verbs:подделать{}, // подделать в документе rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети rus_verbs:растолстеть{}, // растолстеть в талии rus_verbs:повоевать{}, // повоевать в городских условиях rus_verbs:прибраться{}, // гнушаться прибраться в хлеву rus_verbs:поглощаться{}, // поглощаться в металлической фольге rus_verbs:ухать{}, // ухать в лесу rus_verbs:подписываться{}, // подписываться в петиции rus_verbs:покатать{}, // покатать в машинке rus_verbs:излечиться{}, // излечиться в клинике rus_verbs:трепыхаться{}, // трепыхаться в мешке rus_verbs:кипятить{}, // кипятить в кастрюле rus_verbs:понастроить{}, // понастроить в прибрежной зоне rus_verbs:перебывать{}, // перебывать во всех европейских столицах rus_verbs:оглашать{}, // оглашать в итоговой части rus_verbs:преуспевать{}, // преуспевать в новом бизнесе rus_verbs:консультироваться{}, // консультироваться в техподдержке rus_verbs:накапливать{}, // накапливать в печени rus_verbs:перемешать{}, // перемешать в контейнере rus_verbs:наследить{}, // наследить в коридоре rus_verbs:выявиться{}, // выявиться в результе rus_verbs:забулькать{}, // забулькать в болоте rus_verbs:отваривать{}, // отваривать в молоке rus_verbs:запутываться{}, // запутываться в веревках rus_verbs:нагреться{}, // нагреться в микроволновой печке rus_verbs:рыбачить{}, // рыбачить в открытом море rus_verbs:укорениться{}, // укорениться в сознании широких народных масс rus_verbs:умывать{}, // умывать в тазике rus_verbs:защекотать{}, // защекотать в носу rus_verbs:заходиться{}, // заходиться в плаче инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш }, деепричастие:искупав{}, деепричастие:искупая{}, rus_verbs:заморозить{}, // заморозить в холодильнике rus_verbs:закреплять{}, // закреплять в металлическом держателе rus_verbs:расхватать{}, // расхватать в магазине rus_verbs:истязать{}, // истязать в тюремном подвале rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете rus_verbs:подогреть{}, // подогрей в микроволновке rus_verbs:подогревать{}, rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку rus_verbs:проделать{}, // проделать в стене дыру инфинитив:жениться{ вид:соверш }, // жениться в Техасе инфинитив:жениться{ вид:несоверш }, глагол:жениться{ вид:соверш }, глагол:жениться{ вид:несоверш }, деепричастие:женившись{}, деепричастие:женясь{}, прилагательное:женатый{}, прилагательное:женившийся{вид:соверш}, прилагательное:женящийся{}, rus_verbs:всхрапнуть{}, // всхрапнуть во сне rus_verbs:всхрапывать{}, // всхрапывать во сне rus_verbs:ворочаться{}, // Собака ворочается во сне rus_verbs:воссоздаваться{}, // воссоздаваться в памяти rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу инфинитив:атаковать{ вид:соверш }, глагол:атаковать{ вид:несоверш }, глагол:атаковать{ вид:соверш }, прилагательное:атакованный{}, прилагательное:атаковавший{}, прилагательное:атакующий{}, инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени инфинитив:аккумулировать{вид:соверш}, глагол:аккумулировать{вид:несоверш}, глагол:аккумулировать{вид:соверш}, прилагательное:аккумулированный{}, прилагательное:аккумулирующий{}, //прилагательное:аккумулировавший{ вид:несоверш }, прилагательное:аккумулировавший{ вид:соверш }, rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию rus_verbs:вырасти{}, // Он вырос в глазах коллег. rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо. rus_verbs:убить{}, // убить в себе зверя инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани инфинитив:абсорбироваться{ вид:несоверш }, глагол:абсорбироваться{ вид:соверш }, глагол:абсорбироваться{ вид:несоверш }, rus_verbs:поставить{}, // поставить в углу rus_verbs:сжимать{}, // сжимать в кулаке rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы инфинитив:активизироваться{ вид:соверш }, глагол:активизироваться{ вид:несоверш }, глагол:активизироваться{ вид:соверш }, rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе rus_verbs:базировать{}, // установка будет базирована в лесу rus_verbs:барахтаться{}, // дети барахтались в воде rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины rus_verbs:блуждать{}, // Туристы блуждали в лесу rus_verbs:брать{}, // Жена берет деньги в тумбочке rus_verbs:бродить{}, // парочки бродили в парке rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде rus_verbs:вариться{}, // Курица варится в кастрюле rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году rus_verbs:прокручиваться{}, // Ключ прокручивается в замке rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке rus_verbs:храниться{}, // Настройки хранятся в текстовом файле rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле rus_verbs:витать{}, // Мальчик витает в облаках rus_verbs:владычествовать{}, // Король владычествует в стране rus_verbs:властвовать{}, // Олигархи властвовали в стране rus_verbs:возбудить{}, // возбудить в сердце тоску rus_verbs:возбуждать{}, // возбуждать в сердце тоску rus_verbs:возвыситься{}, // возвыситься в глазах современников rus_verbs:возжечь{}, // возжечь в храме огонь rus_verbs:возжечься{}, // Огонь возжёгся в храме rus_verbs:возжигать{}, // возжигать в храме огонь rus_verbs:возжигаться{}, // Огонь возжигается в храме rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь rus_verbs:вознамериться{}, // вознамериться уйти в монастырь rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове rus_verbs:возникнуть{}, // Новые идейки возникли в голове rus_verbs:возродиться{}, // возродиться в новом качестве rus_verbs:возрождать{}, // возрождать в новом качестве rus_verbs:возрождаться{}, // возрождаться в новом амплуа rus_verbs:ворошить{}, // ворошить в камине кочергой золу rus_verbs:воспевать{}, // Поэты воспевают героев в одах rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами rus_verbs:воспеть{}, // Поэты воспели в этой оде героев rus_verbs:воспретить{}, // воспретить в помещении азартные игры rus_verbs:восславить{}, // Поэты восславили в одах rus_verbs:восславлять{}, // Поэты восславляют в одах rus_verbs:восславляться{}, // Героя восславляются в одах rus_verbs:воссоздать{}, // воссоздает в памяти образ человека rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека rus_verbs:воссоздаться{}, // воссоздаться в памяти rus_verbs:вскипятить{}, // вскипятить в чайнике воду rus_verbs:вскипятиться{}, // вскипятиться в чайнике rus_verbs:встретить{}, // встретить в классе старого приятеля rus_verbs:встретиться{}, // встретиться в классе rus_verbs:встречать{}, // встречать в лесу голодного медведя rus_verbs:встречаться{}, // встречаться в кафе rus_verbs:выбривать{}, // выбривать что-то в подмышках rus_verbs:выбрить{}, // выбрить что-то в паху rus_verbs:вывалять{}, // вывалять кого-то в грязи rus_verbs:вываляться{}, // вываляться в грязи rus_verbs:вываривать{}, // вываривать в молоке rus_verbs:вывариваться{}, // вывариваться в молоке rus_verbs:выварить{}, // выварить в молоке rus_verbs:вывариться{}, // вывариться в молоке rus_verbs:выгрызать{}, // выгрызать в сыре отверствие rus_verbs:выгрызть{}, // выгрызть в сыре отверстие rus_verbs:выгуливать{}, // выгуливать в парке собаку rus_verbs:выгулять{}, // выгулять в парке собаку rus_verbs:выдолбить{}, // выдолбить в стволе углубление rus_verbs:выжить{}, // выжить в пустыне rus_verbs:Выискать{}, // Выискать в программе ошибку rus_verbs:выискаться{}, // Ошибка выискалась в программе rus_verbs:выискивать{}, // выискивать в программе ошибку rus_verbs:выискиваться{}, // выискиваться в программе rus_verbs:выкраивать{}, // выкраивать в расписании время rus_verbs:выкраиваться{}, // выкраиваться в расписании инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере глагол:выкупаться{вид:соверш}, rus_verbs:выловить{}, // выловить в пруду rus_verbs:вымачивать{}, // вымачивать в молоке rus_verbs:вымачиваться{}, // вымачиваться в молоке rus_verbs:вынюхивать{}, // вынюхивать в траве следы rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду rus_verbs:выпачкаться{}, // выпачкаться в грязи rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков rus_verbs:выращивать{}, // выращивать в теплице помидоры rus_verbs:выращиваться{}, // выращиваться в теплице rus_verbs:вырыть{}, // вырыть в земле глубокую яму rus_verbs:высадить{}, // высадить в пустынной местности rus_verbs:высадиться{}, // высадиться в пустынной местности rus_verbs:высаживать{}, // высаживать в пустыне rus_verbs:высверливать{}, // высверливать в доске отверствие rus_verbs:высверливаться{}, // высверливаться в стене rus_verbs:высверлить{}, // высверлить в стене отверствие rus_verbs:высверлиться{}, // высверлиться в стене rus_verbs:выскоблить{}, // выскоблить в столешнице канавку rus_verbs:высматривать{}, // высматривать в темноте rus_verbs:заметить{}, // заметить в помещении rus_verbs:оказаться{}, // оказаться в первых рядах rus_verbs:душить{}, // душить в объятиях rus_verbs:оставаться{}, // оставаться в классе rus_verbs:появиться{}, // впервые появиться в фильме rus_verbs:лежать{}, // лежать в футляре rus_verbs:раздаться{}, // раздаться в плечах rus_verbs:ждать{}, // ждать в здании вокзала rus_verbs:жить{}, // жить в трущобах rus_verbs:постелить{}, // постелить в прихожей rus_verbs:оказываться{}, // оказываться в неприятной ситуации rus_verbs:держать{}, // держать в голове rus_verbs:обнаружить{}, // обнаружить в себе способность rus_verbs:начинать{}, // начинать в лаборатории rus_verbs:рассказывать{}, // рассказывать в лицах rus_verbs:ожидать{}, // ожидать в помещении rus_verbs:продолжить{}, // продолжить в помещении rus_verbs:состоять{}, // состоять в группе rus_verbs:родиться{}, // родиться в рубашке rus_verbs:искать{}, // искать в кармане rus_verbs:иметься{}, // иметься в наличии rus_verbs:говориться{}, // говориться в среде панков rus_verbs:клясться{}, // клясться в верности rus_verbs:узнавать{}, // узнавать в нем своего сына rus_verbs:признаться{}, // признаться в ошибке rus_verbs:сомневаться{}, // сомневаться в искренности rus_verbs:толочь{}, // толочь в ступе rus_verbs:понадобиться{}, // понадобиться в суде rus_verbs:служить{}, // служить в пехоте rus_verbs:потолочь{}, // потолочь в ступе rus_verbs:появляться{}, // появляться в театре rus_verbs:сжать{}, // сжать в объятиях rus_verbs:действовать{}, // действовать в постановке rus_verbs:селить{}, // селить в гостинице rus_verbs:поймать{}, // поймать в лесу rus_verbs:увидать{}, // увидать в толпе rus_verbs:подождать{}, // подождать в кабинете rus_verbs:прочесть{}, // прочесть в глазах rus_verbs:тонуть{}, // тонуть в реке rus_verbs:ощущать{}, // ощущать в животе rus_verbs:ошибиться{}, // ошибиться в расчетах rus_verbs:отметить{}, // отметить в списке rus_verbs:показывать{}, // показывать в динамике rus_verbs:скрыться{}, // скрыться в траве rus_verbs:убедиться{}, // убедиться в корректности rus_verbs:прозвучать{}, // прозвучать в наушниках rus_verbs:разговаривать{}, // разговаривать в фойе rus_verbs:издать{}, // издать в России rus_verbs:прочитать{}, // прочитать в газете rus_verbs:попробовать{}, // попробовать в деле rus_verbs:замечать{}, // замечать в программе ошибку rus_verbs:нести{}, // нести в руках rus_verbs:пропасть{}, // пропасть в плену rus_verbs:носить{}, // носить в кармане rus_verbs:гореть{}, // гореть в аду rus_verbs:поправить{}, // поправить в программе rus_verbs:застыть{}, // застыть в неудобной позе rus_verbs:получать{}, // получать в кассе rus_verbs:потребоваться{}, // потребоваться в работе rus_verbs:спрятать{}, // спрятать в шкафу rus_verbs:учиться{}, // учиться в институте rus_verbs:развернуться{}, // развернуться в коридоре rus_verbs:подозревать{}, // подозревать в мошенничестве rus_verbs:играть{}, // играть в команде rus_verbs:сыграть{}, // сыграть в команде rus_verbs:строить{}, // строить в деревне rus_verbs:устроить{}, // устроить в доме вечеринку rus_verbs:находить{}, // находить в лесу rus_verbs:нуждаться{}, // нуждаться в деньгах rus_verbs:испытать{}, // испытать в рабочей обстановке rus_verbs:мелькнуть{}, // мелькнуть в прицеле rus_verbs:очутиться{}, // очутиться в закрытом помещении инфинитив:использовать{вид:соверш}, // использовать в работе инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, глагол:использовать{вид:соверш}, rus_verbs:лететь{}, // лететь в самолете rus_verbs:смеяться{}, // смеяться в цирке rus_verbs:ездить{}, // ездить в лимузине rus_verbs:заснуть{}, // заснуть в неудобной позе rus_verbs:застать{}, // застать в неформальной обстановке rus_verbs:очнуться{}, // очнуться в незнакомой обстановке rus_verbs:твориться{}, // Что творится в закрытой зоне rus_verbs:разглядеть{}, // разглядеть в темноте rus_verbs:изучать{}, // изучать в естественных условиях rus_verbs:удержаться{}, // удержаться в седле rus_verbs:побывать{}, // побывать в зоопарке rus_verbs:уловить{}, // уловить в словах нотку отчаяния rus_verbs:приобрести{}, // приобрести в лавке rus_verbs:исчезать{}, // исчезать в тумане rus_verbs:уверять{}, // уверять в своей невиновности rus_verbs:продолжаться{}, // продолжаться в воздухе rus_verbs:открывать{}, // открывать в городе новый стадион rus_verbs:поддержать{}, // поддержать в парке порядок rus_verbs:солить{}, // солить в бочке rus_verbs:прожить{}, // прожить в деревне rus_verbs:создавать{}, // создавать в театре rus_verbs:обсуждать{}, // обсуждать в коллективе rus_verbs:заказать{}, // заказать в магазине rus_verbs:отыскать{}, // отыскать в гараже rus_verbs:уснуть{}, // уснуть в кресле rus_verbs:задержаться{}, // задержаться в театре rus_verbs:подобрать{}, // подобрать в коллекции rus_verbs:пробовать{}, // пробовать в работе rus_verbs:курить{}, // курить в закрытом помещении rus_verbs:устраивать{}, // устраивать в лесу засаду rus_verbs:установить{}, // установить в багажнике rus_verbs:запереть{}, // запереть в сарае rus_verbs:содержать{}, // содержать в достатке rus_verbs:синеть{}, // синеть в кислородной атмосфере rus_verbs:слышаться{}, // слышаться в голосе rus_verbs:закрыться{}, // закрыться в здании rus_verbs:скрываться{}, // скрываться в квартире rus_verbs:родить{}, // родить в больнице rus_verbs:описать{}, // описать в заметках rus_verbs:перехватить{}, // перехватить в коридоре rus_verbs:менять{}, // менять в магазине rus_verbs:скрывать{}, // скрывать в чужой квартире rus_verbs:стиснуть{}, // стиснуть в стальных объятиях rus_verbs:останавливаться{}, // останавливаться в гостинице rus_verbs:мелькать{}, // мелькать в телевизоре rus_verbs:присутствовать{}, // присутствовать в аудитории rus_verbs:украсть{}, // украсть в магазине rus_verbs:победить{}, // победить в войне rus_verbs:расположиться{}, // расположиться в гостинице rus_verbs:упомянуть{}, // упомянуть в своей книге rus_verbs:плыть{}, // плыть в старой бочке rus_verbs:нащупать{}, // нащупать в глубине rus_verbs:проявляться{}, // проявляться в работе rus_verbs:затихнуть{}, // затихнуть в норе rus_verbs:построить{}, // построить в гараже rus_verbs:поддерживать{}, // поддерживать в исправном состоянии rus_verbs:заработать{}, // заработать в стартапе rus_verbs:сломать{}, // сломать в суставе rus_verbs:снимать{}, // снимать в гардеробе rus_verbs:сохранить{}, // сохранить в коллекции rus_verbs:располагаться{}, // располагаться в отдельном кабинете rus_verbs:сражаться{}, // сражаться в честном бою rus_verbs:спускаться{}, // спускаться в батискафе rus_verbs:уничтожить{}, // уничтожить в схроне rus_verbs:изучить{}, // изучить в естественных условиях rus_verbs:рождаться{}, // рождаться в муках rus_verbs:пребывать{}, // пребывать в прострации rus_verbs:прилететь{}, // прилететь в аэробусе rus_verbs:догнать{}, // догнать в переулке rus_verbs:изобразить{}, // изобразить в танце rus_verbs:проехать{}, // проехать в легковушке rus_verbs:убедить{}, // убедить в разумности rus_verbs:приготовить{}, // приготовить в духовке rus_verbs:собирать{}, // собирать в лесу rus_verbs:поплыть{}, // поплыть в катере rus_verbs:доверять{}, // доверять в управлении rus_verbs:разобраться{}, // разобраться в законах rus_verbs:ловить{}, // ловить в озере rus_verbs:проесть{}, // проесть в куске металла отверстие rus_verbs:спрятаться{}, // спрятаться в подвале rus_verbs:провозгласить{}, // провозгласить в речи rus_verbs:изложить{}, // изложить в своём выступлении rus_verbs:замяться{}, // замяться в коридоре rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна rus_verbs:хранить{}, // хранить в шкатулке rus_verbs:шутить{}, // шутить в классе глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях инфинитив:рассыпаться{ aux stress="рассып^аться" }, rus_verbs:чертить{}, // чертить в тетрадке rus_verbs:отразиться{}, // отразиться в аттестате rus_verbs:греть{}, // греть в микроволновке rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса rus_verbs:рассуждать{}, // Автор рассуждает в своей статье rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда rus_verbs:окружать{}, // окружать в лесу rus_verbs:сопровождать{}, // сопровождать в операции rus_verbs:заканчиваться{}, // заканчиваться в дороге rus_verbs:поселиться{}, // поселиться в загородном доме rus_verbs:охватывать{}, // охватывать в хронологии rus_verbs:запеть{}, // запеть в кино инфинитив:провозить{вид:несоверш}, // провозить в багаже глагол:провозить{вид:несоверш}, rus_verbs:мочить{}, // мочить в сортире rus_verbs:перевернуться{}, // перевернуться в полёте rus_verbs:улететь{}, // улететь в теплые края rus_verbs:сдержать{}, // сдержать в руках rus_verbs:преследовать{}, // преследовать в любой другой стране rus_verbs:драться{}, // драться в баре rus_verbs:просидеть{}, // просидеть в классе rus_verbs:убираться{}, // убираться в квартире rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения rus_verbs:пугать{}, // пугать в прессе rus_verbs:отреагировать{}, // отреагировать в прессе rus_verbs:проверять{}, // проверять в аппарате rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив rus_verbs:летать{}, // летать в комфортабельном частном самолёте rus_verbs:толпиться{}, // толпиться в фойе rus_verbs:плавать{}, // плавать в специальном костюме rus_verbs:пробыть{}, // пробыть в воде слишком долго rus_verbs:прикинуть{}, // прикинуть в уме rus_verbs:застрять{}, // застрять в лифте rus_verbs:метаться{}, // метаться в кровате rus_verbs:сжечь{}, // сжечь в печке rus_verbs:расслабиться{}, // расслабиться в ванной rus_verbs:услыхать{}, // услыхать в автобусе rus_verbs:удержать{}, // удержать в вертикальном положении rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы rus_verbs:рассмотреть{}, // рассмотреть в капле воды rus_verbs:просмотреть{}, // просмотреть в браузере rus_verbs:учесть{}, // учесть в планах rus_verbs:уезжать{}, // уезжать в чьей-то машине rus_verbs:похоронить{}, // похоронить в мерзлой земле rus_verbs:растянуться{}, // растянуться в расслабленной позе rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке rus_verbs:гулять{}, // гулять в парке rus_verbs:утонуть{}, // утонуть в реке rus_verbs:зажать{}, // зажать в медвежьих объятиях rus_verbs:усомниться{}, // усомниться в объективности rus_verbs:танцевать{}, // танцевать в спортзале rus_verbs:проноситься{}, // проноситься в голове rus_verbs:трудиться{}, // трудиться в кооперативе глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный }, rus_verbs:сушить{}, // сушить в сушильном шкафу rus_verbs:зашевелиться{}, // зашевелиться в траве rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке rus_verbs:промелькнуть{}, // промелькнуть в окне rus_verbs:поучаствовать{}, // поучаствовать в обсуждении rus_verbs:закрыть{}, // закрыть в комнате rus_verbs:запирать{}, // запирать в комнате rus_verbs:закрывать{}, // закрывать в доме rus_verbs:заблокировать{}, // заблокировать в доме rus_verbs:зацвести{}, // В садах зацвела сирень rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу. rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе rus_verbs:стоять{}, // войска, стоявшие в Риме rus_verbs:закалить{}, // ветераны, закаленные в боях rus_verbs:выступать{}, // пришлось выступать в тюрьме. rus_verbs:выступить{}, // пришлось выступить в тюрьме. rus_verbs:закопошиться{}, // Мыши закопошились в траве rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре rus_verbs:закрываться{}, // закрываться в комнате rus_verbs:провалиться{}, // провалиться в прокате деепричастие:авторизируясь{ вид:несоверш }, глагол:авторизироваться{ вид:несоверш }, инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе rus_verbs:существовать{}, // существовать в вакууме деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, // находиться в вакууме rus_verbs:регистрировать{}, // регистрировать в инспекции глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш }, инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции rus_verbs:поковыряться{}, // поковыряться в носу rus_verbs:оттаять{}, // оттаять в кипятке rus_verbs:распинаться{}, // распинаться в проклятиях rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения. прилагательное:несчастный{}, // Он очень несчастен в семейной жизни. rus_verbs:объясниться{}, // Он объяснился в любви. прилагательное:нетвердый{}, // Он нетвёрд в истории. rus_verbs:заниматься{}, // Он занимается в читальном зале. rus_verbs:вращаться{}, // Он вращается в учёных кругах. прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне. rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры. rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения. rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев. rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях. rus_verbs:продолжать{}, // Продолжайте в том же духе. rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:болтать{}, // Не болтай в присутствии начальника! rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника! rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине. rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах rus_verbs:сходиться{}, // Все дороги сходятся в Москве rus_verbs:убирать{}, // убирать в комнате rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста rus_verbs:уединяться{}, // уединяться в пустыне rus_verbs:уживаться{}, // уживаться в одном коллективе rus_verbs:укорять{}, // укорять друга в забывчивости rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем rus_verbs:работать{}, // Я работаю в театре. rus_verbs:признать{}, // Я признал в нём старого друга. rus_verbs:преподавать{}, // Я преподаю в университете. rus_verbs:понимать{}, // Я плохо понимаю в живописи. rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа rus_verbs:замереть{}, // вся толпа замерла в восхищении rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле. rus_verbs:идти{}, // Я иду в неопределённом направлении. rus_verbs:заболеть{}, // Я заболел в дороге. rus_verbs:ехать{}, // Я еду в автобусе rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю. rus_verbs:провести{}, // Юные годы он провёл в Италии. rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти. rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении. rus_verbs:произойти{}, // Это произошло в одном городе в Японии. rus_verbs:привидеться{}, // Это мне привиделось во сне. rus_verbs:держаться{}, // Это дело держится в большом секрете. rus_verbs:привиться{}, // Это выражение не привилось в русском языке. rus_verbs:восстановиться{}, // Эти писатели восстановились в правах. rus_verbs:быть{}, // Эта книга есть в любом книжном магазине. прилагательное:популярный{}, // Эта идея очень популярна в массах. rus_verbs:шуметь{}, // Шумит в голове. rus_verbs:остаться{}, // Шляпа осталась в поезде. rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях. rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе. rus_verbs:пересохнуть{}, // У меня в горле пересохло. rus_verbs:щекотать{}, // У меня в горле щекочет. rus_verbs:колоть{}, // У меня в боку колет. прилагательное:свежий{}, // Событие ещё свежо в памяти. rus_verbs:собрать{}, // Соберите всех учеников во дворе. rus_verbs:белеть{}, // Снег белеет в горах. rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте? rus_verbs:таять{}, // Сахар тает в кипятке. rus_verbs:жать{}, // Сапог жмёт в подъёме. rus_verbs:возиться{}, // Ребята возятся в углу. rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме. rus_verbs:кружиться{}, // Они кружились в вальсе. rus_verbs:выставлять{}, // Они выставляют его в смешном виде. rus_verbs:бывать{}, // Она часто бывает в обществе. rus_verbs:петь{}, // Она поёт в опере. rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях. rus_verbs:валяться{}, // Вещи валялись в беспорядке. rus_verbs:пройти{}, // Весь день прошёл в беготне. rus_verbs:продавать{}, // В этом магазине продают обувь. rus_verbs:заключаться{}, // В этом заключается вся сущность. rus_verbs:звенеть{}, // В ушах звенит. rus_verbs:проступить{}, // В тумане проступили очертания корабля. rus_verbs:бить{}, // В саду бьёт фонтан. rus_verbs:проскользнуть{}, // В речи проскользнул упрёк. rus_verbs:оставить{}, // Не оставь товарища в опасности. rus_verbs:прогулять{}, // Мы прогуляли час в парке. rus_verbs:перебить{}, // Мы перебили врагов в бою. rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице. rus_verbs:видеть{}, // Он многое видел в жизни. // глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере. rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах. rus_verbs:кинуть{}, // Он кинул меня в беде. rus_verbs:приходить{}, // Приходи в сентябре rus_verbs:воскрешать{}, // воскрешать в памяти rus_verbs:соединять{}, // соединять в себе rus_verbs:разбираться{}, // умение разбираться в вещах rus_verbs:делать{}, // В её комнате делали обыск. rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина. rus_verbs:начаться{}, // В деревне начались полевые работы. rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль. rus_verbs:вертеться{}, // В голове вертится вчерашний разговор. rus_verbs:веять{}, // В воздухе веет прохладой. rus_verbs:висеть{}, // В воздухе висит зной. rus_verbs:носиться{}, // В воздухе носятся комары. rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее rus_verbs:воскресить{}, // воскресить в памяти rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина прилагательное:уверенный{ причастие }, // Она уверена в своих силах. прилагательное:постоянный{}, // Она постоянна во вкусах. прилагательное:сильный{}, // Он не силён в математике. прилагательное:повинный{}, // Он не повинен в этом. прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве. rus_verbs:сесть{}, // Она села в тени rus_verbs:заливаться{}, // в нашем парке заливаются соловьи rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени // rus_verbs:расти{}, // дерево, растущее в лесу rus_verbs:происходить{}, // что происходит в поликлиннике rus_verbs:спать{}, // кто спит в моей кровати rus_verbs:мыть{}, // мыть машину в саду ГЛ_ИНФ(царить), // В воздухе царило безмолвие ГЛ_ИНФ(мести), // мести в прихожей пол ГЛ_ИНФ(прятать), // прятать в яме ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне. // ГЛ_ИНФ(собраться), // собраться в порту ГЛ_ИНФ(случиться), // что-то случилось в больнице ГЛ_ИНФ(зажечься), // в небе зажглись звёзды ГЛ_ИНФ(купить), // купи молока в магазине прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР } // Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds fact гл_предл { if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } } then return true } // С локативом: // собраться в порту fact гл_предл { if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } } then return true } #endregion Предложный #region Винительный // Для глаголов движения с выраженным направлением действия может присоединяться // предложный паттерн с винительным падежом. wordentry_set Гл_В_Вин = { rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок. глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе. глагол:ввергать{}, инфинитив:ввергнуть{}, инфинитив:ввергать{}, rus_verbs:двинуться{}, // Двинулись в путь и мы. rus_verbs:сплавать{}, // Сплавать в Россию! rus_verbs:уложиться{}, // Уложиться в воскресенье. rus_verbs:спешить{}, // Спешите в Лондон rus_verbs:кинуть{}, // Киньте в море. rus_verbs:проситься{}, // Просилась в Никарагуа. rus_verbs:притопать{}, // Притопал в Будапешт. rus_verbs:скататься{}, // Скатался в Красноярск. rus_verbs:соскользнуть{}, // Соскользнул в пике. rus_verbs:соскальзывать{}, rus_verbs:играть{}, // Играл в дутье. глагол:айда{}, // Айда в каморы. rus_verbs:отзывать{}, // Отзывали в Москву... rus_verbs:сообщаться{}, // Сообщается в Лондон. rus_verbs:вдуматься{}, // Вдумайтесь в них. rus_verbs:проехать{}, // Проехать в Лунево... rus_verbs:спрыгивать{}, // Спрыгиваем в него. rus_verbs:верить{}, // Верю в вас! rus_verbs:прибыть{}, // Прибыл в Подмосковье. rus_verbs:переходить{}, // Переходите в школу. rus_verbs:доложить{}, // Доложили в Москву. rus_verbs:подаваться{}, // Подаваться в Россию? rus_verbs:спрыгнуть{}, // Спрыгнул в него. rus_verbs:вывезти{}, // Вывезли в Китай. rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю. rus_verbs:пропихнуть{}, rus_verbs:транспортироваться{}, rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения rus_verbs:дуть{}, rus_verbs:БОГАТЕТЬ{}, // rus_verbs:РАЗБОГАТЕТЬ{}, // rus_verbs:ВОЗРАСТАТЬ{}, // rus_verbs:ВОЗРАСТИ{}, // rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ) rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ) rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ) rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ) rus_verbs:ЗАМАНИВАТЬ{}, rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ) rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ) rus_verbs:ВРУБАТЬСЯ{}, rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ) rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ) rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ) rus_verbs:ЗАХВАТЫВАТЬ{}, rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ) rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ) rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ) rus_verbs:ПОСТРОИТЬСЯ{}, rus_verbs:ВЫСТРОИТЬСЯ{}, rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ) rus_verbs:ВЫПУСКАТЬ{}, rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ) rus_verbs:ВЦЕПИТЬСЯ{}, rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ) rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ) rus_verbs:ОТСТУПАТЬ{}, rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ) rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ) rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ) rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ) rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ) rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ) rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин) rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ) rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ) rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ) rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ) rus_verbs:СЖИМАТЬСЯ{}, rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ) rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ) rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ) rus_verbs:ПОКРАСИТЬ{}, // rus_verbs:ПЕРЕКРАСИТЬ{}, // rus_verbs:ОКРАСИТЬ{}, // rus_verbs:ЗАКРАСИТЬ{}, // rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ) rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ) rus_verbs:СТЯНУТЬ{}, // rus_verbs:ЗАТЯНУТЬ{}, // rus_verbs:ВТЯНУТЬ{}, // rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ) деепричастие:придя{}, // Немного придя в себя rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ) rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ) rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ) rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ) rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ) rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ) rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин) rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин) rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин) rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин) rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин) rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин) rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин) rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В) rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В) rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В) rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В) rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин) rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В) rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В) rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин) rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В) rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В) rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В) rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В) rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В) rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В) rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В) rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В) rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В) rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны. rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В) rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям. rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В) rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в) rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В) rus_verbs:валить{}, // валить все в одну кучу (валить в) rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в) rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в) rus_verbs:клониться{}, // он клонился в сторону (клониться в) rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в) rus_verbs:запасть{}, // Эти слова запали мне в душу. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:ездить{}, // Каждый день грузовик ездит в город. rus_verbs:претвориться{}, // Замысел претворился в жизнь. rus_verbs:разойтись{}, // Они разошлись в разные стороны. rus_verbs:выйти{}, // Охотник вышел в поле с ружьём. rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом. rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны rus_verbs:переодеваться{}, // переодеваться в женское платье rus_verbs:перерастать{}, // перерастать в массовые беспорядки rus_verbs:завязываться{}, // завязываться в узел rus_verbs:похватать{}, // похватать в руки rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:помещать{}, // помещать в изолятор rus_verbs:зыркнуть{}, // зыркнуть в окошко rus_verbs:закатать{}, // закатать в асфальт rus_verbs:усаживаться{}, // усаживаться в кресло rus_verbs:загонять{}, // загонять в сарай rus_verbs:подбрасывать{}, // подбрасывать в воздух rus_verbs:телеграфировать{}, // телеграфировать в центр rus_verbs:вязать{}, // вязать в стопы rus_verbs:подлить{}, // подлить в огонь rus_verbs:заполучить{}, // заполучить в распоряжение rus_verbs:подогнать{}, // подогнать в док rus_verbs:ломиться{}, // ломиться в открытую дверь rus_verbs:переправить{}, // переправить в деревню rus_verbs:затягиваться{}, // затягиваться в трубу rus_verbs:разлетаться{}, // разлетаться в стороны rus_verbs:кланяться{}, // кланяться в ножки rus_verbs:устремляться{}, // устремляться в открытое море rus_verbs:переместиться{}, // переместиться в другую аудиторию rus_verbs:ложить{}, // ложить в ящик rus_verbs:отвозить{}, // отвозить в аэропорт rus_verbs:напрашиваться{}, // напрашиваться в гости rus_verbs:напроситься{}, // напроситься в гости rus_verbs:нагрянуть{}, // нагрянуть в гости rus_verbs:заворачивать{}, // заворачивать в фольгу rus_verbs:заковать{}, // заковать в кандалы rus_verbs:свезти{}, // свезти в сарай rus_verbs:притащиться{}, // притащиться в дом rus_verbs:завербовать{}, // завербовать в разведку rus_verbs:рубиться{}, // рубиться в компьютерные игры rus_verbs:тыкаться{}, // тыкаться в материнскую грудь инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш }, деепричастие:ссыпав{}, деепричастие:ссыпая{}, rus_verbs:засасывать{}, // засасывать в себя rus_verbs:скакнуть{}, // скакнуть в будущее rus_verbs:подвозить{}, // подвозить в театр rus_verbs:переиграть{}, // переиграть в покер rus_verbs:мобилизовать{}, // мобилизовать в действующую армию rus_verbs:залетать{}, // залетать в закрытое воздушное пространство rus_verbs:подышать{}, // подышать в трубочку rus_verbs:смотаться{}, // смотаться в институт rus_verbs:рассовать{}, // рассовать в кармашки rus_verbs:захаживать{}, // захаживать в дом инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард деепричастие:сгоняя{}, rus_verbs:посылаться{}, // посылаться в порт rus_verbs:отлить{}, // отлить в кастрюлю rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение rus_verbs:поплакать{}, // поплакать в платочек rus_verbs:обуться{}, // обуться в сапоги rus_verbs:закапать{}, // закапать в глаза инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш }, деепричастие:свозив{}, деепричастие:свозя{}, rus_verbs:преобразовать{}, // преобразовать в линейное уравнение rus_verbs:кутаться{}, // кутаться в плед rus_verbs:смещаться{}, // смещаться в сторону rus_verbs:зазывать{}, // зазывать в свой магазин инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш }, деепричастие:трансформируясь{}, деепричастие:трансформировавшись{}, rus_verbs:погружать{}, // погружать в кипящее масло rus_verbs:обыграть{}, // обыграть в теннис rus_verbs:закутать{}, // закутать в одеяло rus_verbs:изливаться{}, // изливаться в воду rus_verbs:закатывать{}, // закатывать в асфальт rus_verbs:мотнуться{}, // мотнуться в банк rus_verbs:избираться{}, // избираться в сенат rus_verbs:наниматься{}, // наниматься в услужение rus_verbs:настучать{}, // настучать в органы rus_verbs:запихивать{}, // запихивать в печку rus_verbs:закапывать{}, // закапывать в нос rus_verbs:засобираться{}, // засобираться в поход rus_verbs:копировать{}, // копировать в другую папку rus_verbs:замуровать{}, // замуровать в стену rus_verbs:упечь{}, // упечь в тюрьму rus_verbs:зрить{}, // зрить в корень rus_verbs:стягиваться{}, // стягиваться в одну точку rus_verbs:усаживать{}, // усаживать в тренажер rus_verbs:протолкнуть{}, // протолкнуть в отверстие rus_verbs:расшибиться{}, // расшибиться в лепешку rus_verbs:приглашаться{}, // приглашаться в кабинет rus_verbs:садить{}, // садить в телегу rus_verbs:уткнуть{}, // уткнуть в подушку rus_verbs:протечь{}, // протечь в подвал rus_verbs:перегнать{}, // перегнать в другую страну rus_verbs:переползти{}, // переползти в тень rus_verbs:зарываться{}, // зарываться в грунт rus_verbs:переодеть{}, // переодеть в сухую одежду rus_verbs:припуститься{}, // припуститься в пляс rus_verbs:лопотать{}, // лопотать в микрофон rus_verbs:прогнусавить{}, // прогнусавить в микрофон rus_verbs:мочиться{}, // мочиться в штаны rus_verbs:загружать{}, // загружать в патронник rus_verbs:радировать{}, // радировать в центр rus_verbs:промотать{}, // промотать в конец rus_verbs:помчать{}, // помчать в школу rus_verbs:съезжать{}, // съезжать в кювет rus_verbs:завозить{}, // завозить в магазин rus_verbs:заявляться{}, // заявляться в школу rus_verbs:наглядеться{}, // наглядеться в зеркало rus_verbs:сворачиваться{}, // сворачиваться в клубочек rus_verbs:устремлять{}, // устремлять взор в будущее rus_verbs:забредать{}, // забредать в глухие уголки rus_verbs:перемотать{}, // перемотать в самое начало диалога rus_verbs:сморкаться{}, // сморкаться в носовой платочек rus_verbs:перетекать{}, // перетекать в другой сосуд rus_verbs:закачать{}, // закачать в шарик rus_verbs:запрятать{}, // запрятать в сейф rus_verbs:пинать{}, // пинать в живот rus_verbs:затрубить{}, // затрубить в горн rus_verbs:подглядывать{}, // подглядывать в замочную скважину инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш }, деепричастие:подсыпав{}, деепричастие:подсыпая{}, rus_verbs:засовывать{}, // засовывать в пенал rus_verbs:отрядить{}, // отрядить в командировку rus_verbs:справлять{}, // справлять в кусты rus_verbs:поторапливаться{}, // поторапливаться в самолет rus_verbs:скопировать{}, // скопировать в кэш rus_verbs:подливать{}, // подливать в огонь rus_verbs:запрячь{}, // запрячь в повозку rus_verbs:окраситься{}, // окраситься в пурпур rus_verbs:уколоть{}, // уколоть в шею rus_verbs:слететься{}, // слететься в гнездо rus_verbs:резаться{}, // резаться в карты rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш) деепричастие:задвигая{}, rus_verbs:доставляться{}, // доставляться в ресторан rus_verbs:поплевать{}, // поплевать в чашку rus_verbs:попереться{}, // попереться в магазин rus_verbs:хаживать{}, // хаживать в церковь rus_verbs:преображаться{}, // преображаться в королеву rus_verbs:организоваться{}, // организоваться в группу rus_verbs:ужалить{}, // ужалить в руку rus_verbs:протискиваться{}, // протискиваться в аудиторию rus_verbs:препроводить{}, // препроводить в закуток rus_verbs:разъезжаться{}, // разъезжаться в разные стороны rus_verbs:пропыхтеть{}, // пропыхтеть в трубку rus_verbs:уволочь{}, // уволочь в нору rus_verbs:отодвигаться{}, // отодвигаться в сторону rus_verbs:разливать{}, // разливать в стаканы rus_verbs:сбегаться{}, // сбегаться в актовый зал rus_verbs:наведаться{}, // наведаться в кладовку rus_verbs:перекочевать{}, // перекочевать в горы rus_verbs:прощебетать{}, // прощебетать в трубку rus_verbs:перекладывать{}, // перекладывать в другой карман rus_verbs:углубляться{}, // углубляться в теорию rus_verbs:переименовать{}, // переименовать в город rus_verbs:переметнуться{}, // переметнуться в лагерь противника rus_verbs:разносить{}, // разносить в щепки rus_verbs:осыпаться{}, // осыпаться в холода rus_verbs:попроситься{}, // попроситься в туалет rus_verbs:уязвить{}, // уязвить в сердце rus_verbs:перетащить{}, // перетащить в дом rus_verbs:закутаться{}, // закутаться в плед // rus_verbs:упаковать{}, // упаковать в бумагу инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость rus_verbs:хихикать{}, // хихикать в кулачок rus_verbs:объединить{}, // объединить в сеть инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию деепричастие:слетав{}, rus_verbs:заползти{}, // заползти в норку rus_verbs:перерасти{}, // перерасти в крупную аферу rus_verbs:списать{}, // списать в утиль rus_verbs:просачиваться{}, // просачиваться в бункер rus_verbs:пускаться{}, // пускаться в погоню rus_verbs:согревать{}, // согревать в мороз rus_verbs:наливаться{}, // наливаться в емкость rus_verbs:унестись{}, // унестись в небо rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф rus_verbs:сигануть{}, // сигануть в воду rus_verbs:окунуть{}, // окунуть в ледяную воду rus_verbs:просочиться{}, // просочиться в сапог rus_verbs:соваться{}, // соваться в толпу rus_verbs:протолкаться{}, // протолкаться в гардероб rus_verbs:заложить{}, // заложить в ломбард rus_verbs:перекатить{}, // перекатить в сарай rus_verbs:поставлять{}, // поставлять в Китай rus_verbs:залезать{}, // залезать в долги rus_verbs:отлучаться{}, // отлучаться в туалет rus_verbs:сбиваться{}, // сбиваться в кучу rus_verbs:зарыть{}, // зарыть в землю rus_verbs:засадить{}, // засадить в тело rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь rus_verbs:переставить{}, // переставить в шкаф rus_verbs:отчалить{}, // отчалить в плавание rus_verbs:набираться{}, // набираться в команду rus_verbs:лягнуть{}, // лягнуть в живот rus_verbs:притворить{}, // притворить в жизнь rus_verbs:проковылять{}, // проковылять в гардероб rus_verbs:прикатить{}, // прикатить в гараж rus_verbs:залететь{}, // залететь в окно rus_verbs:переделать{}, // переделать в мопед rus_verbs:протащить{}, // протащить в совет rus_verbs:обмакнуть{}, // обмакнуть в воду rus_verbs:отклоняться{}, // отклоняться в сторону rus_verbs:запихать{}, // запихать в пакет rus_verbs:избирать{}, // избирать в совет rus_verbs:загрузить{}, // загрузить в буфер rus_verbs:уплывать{}, // уплывать в Париж rus_verbs:забивать{}, // забивать в мерзлоту rus_verbs:потыкать{}, // потыкать в безжизненную тушу rus_verbs:съезжаться{}, // съезжаться в санаторий rus_verbs:залепить{}, // залепить в рыло rus_verbs:набиться{}, // набиться в карманы rus_verbs:уползти{}, // уползти в нору rus_verbs:упрятать{}, // упрятать в камеру rus_verbs:переместить{}, // переместить в камеру анабиоза rus_verbs:закрасться{}, // закрасться в душу rus_verbs:сместиться{}, // сместиться в инфракрасную область rus_verbs:запускать{}, // запускать в серию rus_verbs:потрусить{}, // потрусить в чащобу rus_verbs:забрасывать{}, // забрасывать в чистую воду rus_verbs:переселить{}, // переселить в отдаленную деревню rus_verbs:переезжать{}, // переезжать в новую квартиру rus_verbs:приподнимать{}, // приподнимать в воздух rus_verbs:добавиться{}, // добавиться в конец очереди rus_verbs:убыть{}, // убыть в часть rus_verbs:передвигать{}, // передвигать в соседнюю клетку rus_verbs:добавляться{}, // добавляться в очередь rus_verbs:дописать{}, // дописать в перечень rus_verbs:записываться{}, // записываться в кружок rus_verbs:продаться{}, // продаться в кредитное рабство rus_verbs:переписывать{}, // переписывать в тетрадку rus_verbs:заплыть{}, // заплыть в территориальные воды инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" }, rus_verbs:отбирать{}, // отбирать в гвардию rus_verbs:нашептывать{}, // нашептывать в микрофон rus_verbs:ковылять{}, // ковылять в стойло rus_verbs:прилетать{}, // прилетать в Париж rus_verbs:пролиться{}, // пролиться в канализацию rus_verbs:запищать{}, // запищать в микрофон rus_verbs:подвезти{}, // подвезти в больницу rus_verbs:припереться{}, // припереться в театр rus_verbs:утечь{}, // утечь в сеть rus_verbs:прорываться{}, // прорываться в буфет rus_verbs:увозить{}, // увозить в ремонт rus_verbs:съедать{}, // съедать в обед rus_verbs:просунуться{}, // просунуться в дверь rus_verbs:перенестись{}, // перенестись в прошлое rus_verbs:завезти{}, // завезти в магазин rus_verbs:проложить{}, // проложить в деревню rus_verbs:объединяться{}, // объединяться в профсоюз rus_verbs:развиться{}, // развиться в бабочку rus_verbs:засеменить{}, // засеменить в кабинку rus_verbs:скатываться{}, // скатываться в яму rus_verbs:завозиться{}, // завозиться в магазин rus_verbs:нанимать{}, // нанимать в рейс rus_verbs:поспеть{}, // поспеть в класс rus_verbs:кидаться{}, // кинаться в крайности rus_verbs:поспевать{}, // поспевать в оперу rus_verbs:обернуть{}, // обернуть в фольгу rus_verbs:обратиться{}, // обратиться в прокуратуру rus_verbs:истолковать{}, // истолковать в свою пользу rus_verbs:таращиться{}, // таращиться в дисплей rus_verbs:прыснуть{}, // прыснуть в кулачок rus_verbs:загнуть{}, // загнуть в другую сторону rus_verbs:раздать{}, // раздать в разные руки rus_verbs:назначить{}, // назначить в приемную комиссию rus_verbs:кидать{}, // кидать в кусты rus_verbs:увлекать{}, // увлекать в лес rus_verbs:переселиться{}, // переселиться в чужое тело rus_verbs:присылать{}, // присылать в город rus_verbs:уплыть{}, // уплыть в Европу rus_verbs:запричитать{}, // запричитать в полный голос rus_verbs:утащить{}, // утащить в логово rus_verbs:завернуться{}, // завернуться в плед rus_verbs:заносить{}, // заносить в блокнот rus_verbs:пятиться{}, // пятиться в дом rus_verbs:наведываться{}, // наведываться в больницу rus_verbs:нырять{}, // нырять в прорубь rus_verbs:зачастить{}, // зачастить в бар rus_verbs:назначаться{}, // назначается в комиссию rus_verbs:мотаться{}, // мотаться в областной центр rus_verbs:разыграть{}, // разыграть в карты rus_verbs:пропищать{}, // пропищать в микрофон rus_verbs:пихнуть{}, // пихнуть в бок rus_verbs:эмигрировать{}, // эмигрировать в Канаду rus_verbs:подключить{}, // подключить в сеть rus_verbs:упереть{}, // упереть в фундамент rus_verbs:уплатить{}, // уплатить в кассу rus_verbs:потащиться{}, // потащиться в медпункт rus_verbs:пригнать{}, // пригнать в стойло rus_verbs:оттеснить{}, // оттеснить в фойе rus_verbs:стучаться{}, // стучаться в ворота rus_verbs:перечислить{}, // перечислить в фонд rus_verbs:сомкнуть{}, // сомкнуть в круг rus_verbs:закачаться{}, // закачаться в резервуар rus_verbs:кольнуть{}, // кольнуть в бок rus_verbs:накрениться{}, // накрениться в сторону берега rus_verbs:подвинуться{}, // подвинуться в другую сторону rus_verbs:разнести{}, // разнести в клочья rus_verbs:отливать{}, // отливать в форму rus_verbs:подкинуть{}, // подкинуть в карман rus_verbs:уводить{}, // уводить в кабинет rus_verbs:ускакать{}, // ускакать в школу rus_verbs:ударять{}, // ударять в барабаны rus_verbs:даться{}, // даться в руки rus_verbs:поцеловаться{}, // поцеловаться в губы rus_verbs:посветить{}, // посветить в подвал rus_verbs:тыкать{}, // тыкать в арбуз rus_verbs:соединяться{}, // соединяться в кольцо rus_verbs:растянуть{}, // растянуть в тонкую ниточку rus_verbs:побросать{}, // побросать в пыль rus_verbs:стукнуться{}, // стукнуться в закрытую дверь rus_verbs:проигрывать{}, // проигрывать в теннис rus_verbs:дунуть{}, // дунуть в трубочку rus_verbs:улетать{}, // улетать в Париж rus_verbs:переводиться{}, // переводиться в филиал rus_verbs:окунуться{}, // окунуться в водоворот событий rus_verbs:попрятаться{}, // попрятаться в норы rus_verbs:перевезти{}, // перевезти в соседнюю палату rus_verbs:топать{}, // топать в школу rus_verbs:относить{}, // относить в помещение rus_verbs:укладывать{}, // укладывать в стопку rus_verbs:укатить{}, // укатил в турне rus_verbs:убирать{}, // убирать в сумку rus_verbs:помалкивать{}, // помалкивать в тряпочку rus_verbs:ронять{}, // ронять в грязь rus_verbs:глазеть{}, // глазеть в бинокль rus_verbs:преобразиться{}, // преобразиться в другого человека rus_verbs:запрыгнуть{}, // запрыгнуть в поезд rus_verbs:сгодиться{}, // сгодиться в суп rus_verbs:проползти{}, // проползти в нору rus_verbs:забираться{}, // забираться в коляску rus_verbs:сбежаться{}, // сбежались в класс rus_verbs:закатиться{}, // закатиться в угол rus_verbs:плевать{}, // плевать в душу rus_verbs:поиграть{}, // поиграть в демократию rus_verbs:кануть{}, // кануть в небытие rus_verbs:опаздывать{}, // опаздывать в школу rus_verbs:отползти{}, // отползти в сторону rus_verbs:стекаться{}, // стекаться в отстойник rus_verbs:запихнуть{}, // запихнуть в пакет rus_verbs:вышвырнуть{}, // вышвырнуть в коридор rus_verbs:связываться{}, // связываться в плотный узел rus_verbs:затолкать{}, // затолкать в ухо rus_verbs:скрутить{}, // скрутить в трубочку rus_verbs:сворачивать{}, // сворачивать в трубочку rus_verbs:сплестись{}, // сплестись в узел rus_verbs:заскочить{}, // заскочить в кабинет rus_verbs:проваливаться{}, // проваливаться в сон rus_verbs:уверовать{}, // уверовать в свою безнаказанность rus_verbs:переписать{}, // переписать в тетрадку rus_verbs:переноситься{}, // переноситься в мир фантазий rus_verbs:заводить{}, // заводить в помещение rus_verbs:сунуться{}, // сунуться в аудиторию rus_verbs:устраиваться{}, // устраиваться в автомастерскую rus_verbs:пропускать{}, // пропускать в зал инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш }, деепричастие:сбегая{}, деепричастие:сбегав{}, rus_verbs:прибегать{}, // прибегать в школу rus_verbs:съездить{}, // съездить в лес rus_verbs:захлопать{}, // захлопать в ладошки rus_verbs:опрокинуться{}, // опрокинуться в грязь инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш }, деепричастие:насыпая{}, деепричастие:насыпав{}, rus_verbs:употреблять{}, // употреблять в пищу rus_verbs:приводиться{}, // приводиться в действие rus_verbs:пристроить{}, // пристроить в надежные руки rus_verbs:юркнуть{}, // юркнуть в нору rus_verbs:объединиться{}, // объединиться в банду rus_verbs:сажать{}, // сажать в одиночку rus_verbs:соединить{}, // соединить в кольцо rus_verbs:забрести{}, // забрести в кафешку rus_verbs:свернуться{}, // свернуться в клубочек rus_verbs:пересесть{}, // пересесть в другой автобус rus_verbs:постучаться{}, // постучаться в дверцу rus_verbs:соединять{}, // соединять в кольцо rus_verbs:приволочь{}, // приволочь в коморку rus_verbs:смахивать{}, // смахивать в ящик стола rus_verbs:забежать{}, // забежать в помещение rus_verbs:целиться{}, // целиться в беглеца rus_verbs:прокрасться{}, // прокрасться в хранилище rus_verbs:заковылять{}, // заковылять в травтамологию rus_verbs:прискакать{}, // прискакать в стойло rus_verbs:колотить{}, // колотить в дверь rus_verbs:смотреться{}, // смотреться в зеркало rus_verbs:подложить{}, // подложить в салон rus_verbs:пущать{}, // пущать в королевские покои rus_verbs:согнуть{}, // согнуть в дугу rus_verbs:забарабанить{}, // забарабанить в дверь rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы rus_verbs:убраться{}, // убраться в специальную нишу rus_verbs:насмотреться{}, // насмотреться в зеркало rus_verbs:чмокнуть{}, // чмокнуть в щечку rus_verbs:усмехаться{}, // усмехаться в бороду rus_verbs:передвинуть{}, // передвинуть в конец очереди rus_verbs:допускаться{}, // допускаться в опочивальню rus_verbs:задвинуть{}, // задвинуть в дальний угол rus_verbs:отправлять{}, // отправлять в центр rus_verbs:сбрасывать{}, // сбрасывать в жерло rus_verbs:расстреливать{}, // расстреливать в момент обнаружения rus_verbs:заволочь{}, // заволочь в закуток rus_verbs:пролить{}, // пролить в воду rus_verbs:зарыться{}, // зарыться в сено rus_verbs:переливаться{}, // переливаться в емкость rus_verbs:затащить{}, // затащить в клуб rus_verbs:перебежать{}, // перебежать в лагерь врагов rus_verbs:одеть{}, // одеть в новое платье инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу деепричастие:задвигаясь{}, rus_verbs:клюнуть{}, // клюнуть в темечко rus_verbs:наливать{}, // наливать в кружку rus_verbs:пролезть{}, // пролезть в ушко rus_verbs:откладывать{}, // откладывать в ящик rus_verbs:протянуться{}, // протянуться в соседний дом rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь rus_verbs:устанавливать{}, // устанавливать в машину rus_verbs:употребляться{}, // употребляться в пищу rus_verbs:переключиться{}, // переключиться в реверсный режим rus_verbs:пискнуть{}, // пискнуть в микрофон rus_verbs:заявиться{}, // заявиться в класс rus_verbs:налиться{}, // налиться в стакан rus_verbs:заливать{}, // заливать в бак rus_verbs:ставиться{}, // ставиться в очередь инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны деепричастие:писаясь{}, rus_verbs:целоваться{}, // целоваться в губы rus_verbs:наносить{}, // наносить в область сердца rus_verbs:посмеяться{}, // посмеяться в кулачок rus_verbs:употребить{}, // употребить в пищу rus_verbs:прорваться{}, // прорваться в столовую rus_verbs:укладываться{}, // укладываться в ровные стопки rus_verbs:пробиться{}, // пробиться в финал rus_verbs:забить{}, // забить в землю rus_verbs:переложить{}, // переложить в другой карман rus_verbs:опускать{}, // опускать в свежевырытую могилу rus_verbs:поторопиться{}, // поторопиться в школу rus_verbs:сдвинуться{}, // сдвинуться в сторону rus_verbs:капать{}, // капать в смесь rus_verbs:погружаться{}, // погружаться во тьму rus_verbs:направлять{}, // направлять в кабинку rus_verbs:погрузить{}, // погрузить во тьму rus_verbs:примчаться{}, // примчаться в школу rus_verbs:упираться{}, // упираться в дверь rus_verbs:удаляться{}, // удаляться в комнату совещаний rus_verbs:ткнуться{}, // ткнуться в окошко rus_verbs:убегать{}, // убегать в чащу rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру rus_verbs:наговорить{}, // наговорить в микрофон rus_verbs:переносить{}, // переносить в дом rus_verbs:прилечь{}, // прилечь в кроватку rus_verbs:поворачивать{}, // поворачивать в обратную сторону rus_verbs:проскочить{}, // проскочить в щель rus_verbs:совать{}, // совать в духовку rus_verbs:переодеться{}, // переодеться в чистую одежду rus_verbs:порвать{}, // порвать в лоскуты rus_verbs:завязать{}, // завязать в бараний рог rus_verbs:съехать{}, // съехать в кювет rus_verbs:литься{}, // литься в канистру rus_verbs:уклониться{}, // уклониться в левую сторону rus_verbs:смахнуть{}, // смахнуть в мусорное ведро rus_verbs:спускать{}, // спускать в шахту rus_verbs:плеснуть{}, // плеснуть в воду rus_verbs:подуть{}, // подуть в угольки rus_verbs:набирать{}, // набирать в команду rus_verbs:хлопать{}, // хлопать в ладошки rus_verbs:ранить{}, // ранить в самое сердце rus_verbs:посматривать{}, // посматривать в иллюминатор rus_verbs:превращать{}, // превращать воду в вино rus_verbs:толкать{}, // толкать в пучину rus_verbs:отбыть{}, // отбыть в расположение части rus_verbs:сгрести{}, // сгрести в карман rus_verbs:удрать{}, // удрать в тайгу rus_verbs:пристроиться{}, // пристроиться в хорошую фирму rus_verbs:сбиться{}, // сбиться в плотную группу rus_verbs:заключать{}, // заключать в объятия rus_verbs:отпускать{}, // отпускать в поход rus_verbs:устремить{}, // устремить взгляд в будущее rus_verbs:обронить{}, // обронить в траву rus_verbs:сливаться{}, // сливаться в речку rus_verbs:стекать{}, // стекать в канаву rus_verbs:свалить{}, // свалить в кучу rus_verbs:подтянуть{}, // подтянуть в кабину rus_verbs:скатиться{}, // скатиться в канаву rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь rus_verbs:заторопиться{}, // заторопиться в буфет rus_verbs:протиснуться{}, // протиснуться в центр толпы rus_verbs:прятать{}, // прятать в укромненькое местечко rus_verbs:пропеть{}, // пропеть в микрофон rus_verbs:углубиться{}, // углубиться в джунгли rus_verbs:сползти{}, // сползти в яму rus_verbs:записывать{}, // записывать в память rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР) rus_verbs:колотиться{}, // колотиться в дверь rus_verbs:просунуть{}, // просунуть в отверстие rus_verbs:провожать{}, // провожать в армию rus_verbs:катить{}, // катить в гараж rus_verbs:поражать{}, // поражать в самое сердце rus_verbs:отлететь{}, // отлететь в дальний угол rus_verbs:закинуть{}, // закинуть в речку rus_verbs:катиться{}, // катиться в пропасть rus_verbs:забросить{}, // забросить в дальний угол rus_verbs:отвезти{}, // отвезти в лагерь rus_verbs:втопить{}, // втопить педаль в пол rus_verbs:втапливать{}, // втапливать педать в пол rus_verbs:утопить{}, // утопить кнопку в панель rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?) rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег rus_verbs:поскакать{}, // поскакать в атаку rus_verbs:прицелиться{}, // прицелиться в бегущего зайца rus_verbs:прыгать{}, // прыгать в кровать rus_verbs:приглашать{}, // приглашать в дом rus_verbs:понестись{}, // понестись в ворота rus_verbs:заехать{}, // заехать в гаражный бокс rus_verbs:опускаться{}, // опускаться в бездну rus_verbs:переехать{}, // переехать в коттедж rus_verbs:поместить{}, // поместить в карантин rus_verbs:ползти{}, // ползти в нору rus_verbs:добавлять{}, // добавлять в корзину rus_verbs:уткнуться{}, // уткнуться в подушку rus_verbs:продавать{}, // продавать в рабство rus_verbs:спрятаться{}, // Белка спрячется в дупло. rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию rus_verbs:воткнуть{}, // воткни вилку в розетку rus_verbs:нести{}, // нести в больницу rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку rus_verbs:впаивать{}, // впаивать деталь в плату rus_verbs:впаиваться{}, // деталь впаивается в плату rus_verbs:впархивать{}, // впархивать в помещение rus_verbs:впаять{}, // впаять деталь в плату rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат rus_verbs:вперивать{}, // вперивать взгляд в экран rus_verbs:впериваться{}, // впериваться в экран rus_verbs:вперить{}, // вперить взгляд в экран rus_verbs:впериться{}, // впериться в экран rus_verbs:вперять{}, // вперять взгляд в экран rus_verbs:вперяться{}, // вперяться в экран rus_verbs:впечатать{}, // впечатать текст в первую главу rus_verbs:впечататься{}, // впечататься в стену rus_verbs:впечатывать{}, // впечатывать текст в первую главу rus_verbs:впечатываться{}, // впечатываться в стену rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами rus_verbs:впитаться{}, // Жидкость впиталась в ткань rus_verbs:впитываться{}, // Жидкость впитывается в ткань rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник rus_verbs:вплавиться{}, // Провод вплавился в плату rus_verbs:вплеснуть{}, // вплеснуть краситель в бак rus_verbs:вплести{}, // вплести ленту в волосы rus_verbs:вплестись{}, // вплестись в волосы rus_verbs:вплетать{}, // вплетать ленты в волосы rus_verbs:вплывать{}, // корабль вплывает в порт rus_verbs:вплыть{}, // яхта вплыла в бухту rus_verbs:вползать{}, // дракон вползает в пещеру rus_verbs:вползти{}, // дракон вполз в свою пещеру rus_verbs:впорхнуть{}, // бабочка впорхнула в окно rus_verbs:впрессовать{}, // впрессовать деталь в плиту rus_verbs:впрессоваться{}, // впрессоваться в плиту rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту rus_verbs:впрессовываться{}, // впрессовываться в плиту rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания rus_verbs:впрягать{}, // впрягать лошадь в телегу rus_verbs:впрягаться{}, // впрягаться в работу rus_verbs:впрячь{}, // впрячь лошадь в телегу rus_verbs:впрячься{}, // впрячься в работу rus_verbs:впускать{}, // впускать посетителей в музей rus_verbs:впускаться{}, // впускаться в помещение rus_verbs:впустить{}, // впустить посетителей в музей rus_verbs:впутать{}, // впутать кого-то во что-то rus_verbs:впутаться{}, // впутаться во что-то rus_verbs:впутывать{}, // впутывать кого-то во что-то rus_verbs:впутываться{}, // впутываться во что-то rus_verbs:врабатываться{}, // врабатываться в режим rus_verbs:вработаться{}, // вработаться в режим rus_verbs:врастать{}, // врастать в кожу rus_verbs:врасти{}, // врасти в кожу инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь инфинитив:врезать{ вид:соверш }, глагол:врезать{ вид:несоверш }, глагол:врезать{ вид:соверш }, деепричастие:врезая{}, деепричастие:врезав{}, прилагательное:врезанный{}, инфинитив:врезаться{ вид:несоверш }, // врезаться в стену инфинитив:врезаться{ вид:соверш }, глагол:врезаться{ вид:несоверш }, деепричастие:врезаясь{}, деепричастие:врезавшись{}, rus_verbs:врубить{}, // врубить в нагрузку rus_verbs:врываться{}, // врываться в здание rus_verbs:закачивать{}, // Насос закачивает топливо в бак rus_verbs:ввезти{}, // Предприятие ввезло товар в страну rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу rus_verbs:ввивать{}, // Женщина ввивает полоску в косу rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека rus_verbs:вламываться{}, // Полиция вламывается в квартиру rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом rus_verbs:вовлечься{}, // вовлечься в занятие спортом rus_verbs:спуститься{}, // спуститься в подвал rus_verbs:спускаться{}, // спускаться в подвал rus_verbs:отправляться{}, // отправляться в дальнее плавание инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство инфинитив:эмитировать{ вид:несоверш }, глагол:эмитировать{ вид:соверш }, глагол:эмитировать{ вид:несоверш }, деепричастие:эмитируя{}, деепричастие:эмитировав{}, прилагательное:эмитировавший{ вид:несоверш }, // прилагательное:эмитировавший{ вид:соверш }, прилагательное:эмитирующий{}, прилагательное:эмитируемый{}, прилагательное:эмитированный{}, инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию инфинитив:этапировать{вид:соверш}, глагол:этапировать{вид:несоверш}, глагол:этапировать{вид:соверш}, деепричастие:этапируя{}, прилагательное:этапируемый{}, прилагательное:этапированный{}, rus_verbs:этапироваться{}, // Преступники этапируются в колонию rus_verbs:баллотироваться{}, // они баллотировались в жюри rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну rus_verbs:бросать{}, // Они бросали в фонтан медные монетки rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:бросить{}, // Он бросил в фонтан медную монетку rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя rus_verbs:буксировать{}, // Буксир буксирует танкер в порт rus_verbs:буксироваться{}, // Сухогруз буксируется в порт rus_verbs:вбегать{}, // Курьер вбегает в дверь rus_verbs:вбежать{}, // Курьер вбежал в дверь rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту rus_verbs:вбиваться{}, // Штырь вбивается в плиту rus_verbs:вбирать{}, // Вата вбирает в себя влагу rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру rus_verbs:вбросить{}, // Судья вбросил мяч в игру rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту rus_verbs:ввариваться{}, // Арматура вваривается в плиту rus_verbs:вварить{}, // Робот вварил арматурину в плиту rus_verbs:влезть{}, // Предприятие ввезло товар в страну rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача rus_verbs:вверяться{}, // Пациент вверяется в руки врача rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров rus_verbs:ввиваться{}, // полоска ввивается в косу rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров // rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон rus_verbs:ввязаться{}, // Разведрота ввязалась в бой rus_verbs:ввязываться{}, // Передовые части ввязываются в бой rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь rus_verbs:вдвинуться{}, // деталь вдвинулась в печь rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко rus_verbs:вделать{}, // мастер вделал розетку в стену rus_verbs:вделывать{}, // мастер вделывает выключатель в стену rus_verbs:вделываться{}, // кронштейн вделывается в стену rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку rus_verbs:вернуться{}, // Дети вернулись в библиотеку rus_verbs:вжаться{}, // Водитель вжался в кресло rus_verbs:вживаться{}, // Актер вживается в новую роль rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента rus_verbs:вживляться{}, // Стимулятор вживляется в тело rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло rus_verbs:вжиться{}, // Актер вжился в свою новую роль rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо rus_verbs:взвинтиться{}, // Цены взвинтились в небо rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо rus_verbs:взвиться{}, // Шарики взвились в небо rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо rus_verbs:взмывать{}, // шарики взмывают в небо rus_verbs:взмыть{}, // Шарики взмыли в небо rus_verbs:вильнуть{}, // Машина вильнула в левую сторону rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю rus_verbs:вкапываться{}, // Свая вкапывается в землю rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж rus_verbs:вкатиться{}, // машина вкатилась в гараж rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж rus_verbs:вкатываться{}, // машина вкатывается в гараж rus_verbs:вкачать{}, // Механики вкачали в бак много топлива rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак rus_verbs:вкачиваться{}, // Топливо вкачивается в бак rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер rus_verbs:вкидываться{}, // Груз вкидывается в контейнер rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции rus_verbs:вкладываться{}, // Инвестор вкладывается в акции rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист rus_verbs:вклиниваться{}, // Машина вклинивается в поток rus_verbs:вклиниться{}, // машина вклинилась в поток rus_verbs:включать{}, // Команда включает компьютер в сеть rus_verbs:включаться{}, // Машина включается в глобальную сеть rus_verbs:включить{}, // Команда включила компьютер в сеть rus_verbs:включиться{}, // Компьютер включился в сеть rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон rus_verbs:влазить{}, // Разъем влазит в отверствие rus_verbs:вламывать{}, // Полиция вламывается в квартиру rus_verbs:влетать{}, // Самолет влетает в грозовой фронт rus_verbs:влететь{}, // Самолет влетел в грозовой фронт rus_verbs:вливать{}, // Механик вливает масло в картер rus_verbs:вливаться{}, // Масло вливается в картер rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности rus_verbs:влить{}, // Механик влил свежее масло в картер rus_verbs:влиться{}, // Свежее масло влилось в бак rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства rus_verbs:вложиться{}, // Инвесторы вложились в эти акции rus_verbs:влюбиться{}, // Коля влюбился в Олю rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов rus_verbs:вляпаться{}, // Коля вляпался в неприятность rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности rus_verbs:вменить{}, // вменить в вину rus_verbs:вменять{}, // вменять в обязанность rus_verbs:вмерзать{}, // Колеса вмерзают в лед rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед rus_verbs:вмести{}, // вмести в дом rus_verbs:вместить{}, // вместить в ёмкость rus_verbs:вместиться{}, // Прибор не вместился в зонд rus_verbs:вмешаться{}, // Начальник вмешался в конфликт rus_verbs:вмешивать{}, // Не вмешивай меня в это дело rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус rus_verbs:вминать{}, // вминать в корпус rus_verbs:вминаться{}, // кронштейн вминается в корпус rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт rus_verbs:вморозить{}, // Установка вморозила сваи в грунт rus_verbs:вмуровать{}, // Сейф был вмурован в стену rus_verbs:вмуровывать{}, // вмуровывать сейф в стену rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену rus_verbs:внедрить{}, // внедрить инновацию в производство rus_verbs:внедриться{}, // Шпион внедрился в руководство rus_verbs:внедрять{}, // внедрять инновации в производство rus_verbs:внедряться{}, // Шпионы внедряются в руководство rus_verbs:внести{}, // внести коробку в дом rus_verbs:внестись{}, // внестись в список приглашенных гостей rus_verbs:вникать{}, // Разработчик вникает в детали задачи rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев rus_verbs:вноситься{}, // вноситься в список главных персонажей rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом rus_verbs:вогнать{}, // вогнал человека в тоску rus_verbs:водворить{}, // водворить преступника в тюрьму rus_verbs:возвернуть{}, // возвернуть в родную стихию rus_verbs:возвернуться{}, // возвернуться в родную стихию rus_verbs:возвести{}, // возвести число в четную степень rus_verbs:возводить{}, // возводить число в четную степень rus_verbs:возводиться{}, // число возводится в четную степень rus_verbs:возвратить{}, // возвратить коров в стойло rus_verbs:возвратиться{}, // возвратиться в родной дом rus_verbs:возвращать{}, // возвращать коров в стойло rus_verbs:возвращаться{}, // возвращаться в родной дом rus_verbs:войти{}, // войти в галерею славы rus_verbs:вонзать{}, // Коля вонзает вилку в котлету rus_verbs:вонзаться{}, // Вилка вонзается в котлету rus_verbs:вонзить{}, // Коля вонзил вилку в котлету rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность rus_verbs:воплотиться{}, // Мечты воплотились в реальность rus_verbs:воплощать{}, // Коля воплощает мечты в реальность rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь rus_verbs:воспарить{}, // Душа воспарила в небо rus_verbs:воспарять{}, // Душа воспаряет в небо rus_verbs:врыть{}, // врыть опору в землю rus_verbs:врыться{}, // врыться в землю rus_verbs:всадить{}, // всадить пулю в сердце rus_verbs:всаживать{}, // всаживать нож в бок rus_verbs:всасывать{}, // всасывать воду в себя rus_verbs:всасываться{}, // всасываться в ёмкость rus_verbs:вселить{}, // вселить надежду в кого-либо rus_verbs:вселиться{}, // вселиться в пустующее здание rus_verbs:вселять{}, // вселять надежду в кого-то rus_verbs:вселяться{}, // вселяться в пустующее здание rus_verbs:вскидывать{}, // вскидывать руку в небо rus_verbs:вскинуть{}, // вскинуть руку в небо rus_verbs:вслушаться{}, // вслушаться в звуки rus_verbs:вслушиваться{}, // вслушиваться в шорох rus_verbs:всматриваться{}, // всматриваться в темноту rus_verbs:всмотреться{}, // всмотреться в темень rus_verbs:всовывать{}, // всовывать палец в отверстие rus_verbs:всовываться{}, // всовываться в форточку rus_verbs:всосать{}, // всосать жидкость в себя rus_verbs:всосаться{}, // всосаться в кожу rus_verbs:вставить{}, // вставить ключ в замок rus_verbs:вставлять{}, // вставлять ключ в замок rus_verbs:встраивать{}, // встраивать черный ход в систему защиты rus_verbs:встраиваться{}, // встраиваться в систему безопасности rus_verbs:встревать{}, // встревать в разговор rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности rus_verbs:встроиться{}, // встроиться в систему безопасности rus_verbs:встрять{}, // встрять в разговор rus_verbs:вступать{}, // вступать в действующую армию rus_verbs:вступить{}, // вступить в действующую армию rus_verbs:всунуть{}, // всунуть палец в отверстие rus_verbs:всунуться{}, // всунуться в форточку инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер инфинитив:всыпать{вид:несоверш}, глагол:всыпать{вид:соверш}, глагол:всыпать{вид:несоверш}, деепричастие:всыпав{}, деепричастие:всыпая{}, прилагательное:всыпавший{ вид:соверш }, // прилагательное:всыпавший{ вид:несоверш }, прилагательное:всыпанный{}, // прилагательное:всыпающий{}, инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер // инфинитив:всыпаться{ вид:соверш}, // глагол:всыпаться{ вид:соверш}, глагол:всыпаться{ вид:несоверш}, // деепричастие:всыпавшись{}, деепричастие:всыпаясь{}, // прилагательное:всыпавшийся{ вид:соверш }, // прилагательное:всыпавшийся{ вид:несоверш }, // прилагательное:всыпающийся{}, rus_verbs:вталкивать{}, // вталкивать деталь в ячейку rus_verbs:вталкиваться{}, // вталкиваться в ячейку rus_verbs:втаптывать{}, // втаптывать в грязь rus_verbs:втаптываться{}, // втаптываться в грязь rus_verbs:втаскивать{}, // втаскивать мешок в комнату rus_verbs:втаскиваться{}, // втаскиваться в комнату rus_verbs:втащить{}, // втащить мешок в комнату rus_verbs:втащиться{}, // втащиться в комнату rus_verbs:втекать{}, // втекать в бутылку rus_verbs:втемяшивать{}, // втемяшивать в голову rus_verbs:втемяшиваться{}, // втемяшиваться в голову rus_verbs:втемяшить{}, // втемяшить в голову rus_verbs:втемяшиться{}, // втемяшиться в голову rus_verbs:втереть{}, // втереть крем в кожу rus_verbs:втереться{}, // втереться в кожу rus_verbs:втесаться{}, // втесаться в группу rus_verbs:втесывать{}, // втесывать в группу rus_verbs:втесываться{}, // втесываться в группу rus_verbs:втечь{}, // втечь в бак rus_verbs:втирать{}, // втирать крем в кожу rus_verbs:втираться{}, // втираться в кожу rus_verbs:втискивать{}, // втискивать сумку в вагон rus_verbs:втискиваться{}, // втискиваться в переполненный вагон rus_verbs:втиснуть{}, // втиснуть сумку в вагон rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро rus_verbs:втолкать{}, // втолкать коляску в лифт rus_verbs:втолкаться{}, // втолкаться в вагон метро rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт rus_verbs:втолкнуться{}, // втолкнуться в вагон метро rus_verbs:втолочь{}, // втолочь в смесь rus_verbs:втоптать{}, // втоптать цветы в землю rus_verbs:вторгаться{}, // вторгаться в чужую зону rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь rus_verbs:втравить{}, // втравить кого-то в неприятности rus_verbs:втравливать{}, // втравливать кого-то в неприятности rus_verbs:втрамбовать{}, // втрамбовать камни в землю rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю rus_verbs:втрамбовываться{}, // втрамбовываться в землю rus_verbs:втрескаться{}, // втрескаться в кого-то rus_verbs:втрескиваться{}, // втрескиваться в кого-либо rus_verbs:втыкать{}, // втыкать вилку в котлетку rus_verbs:втыкаться{}, // втыкаться в розетку rus_verbs:втюриваться{}, // втюриваться в кого-либо rus_verbs:втюриться{}, // втюриться в кого-либо rus_verbs:втягивать{}, // втягивать что-то в себя rus_verbs:втягиваться{}, // втягиваться в себя rus_verbs:втянуться{}, // втянуться в себя rus_verbs:вцементировать{}, // вцементировать сваю в фундамент rus_verbs:вчеканить{}, // вчеканить надпись в лист rus_verbs:вчитаться{}, // вчитаться внимательнее в текст rus_verbs:вчитываться{}, // вчитываться внимательнее в текст rus_verbs:вчувствоваться{}, // вчувствоваться в роль rus_verbs:вшагивать{}, // вшагивать в новую жизнь rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь rus_verbs:вшивать{}, // вшивать заплату в рубашку rus_verbs:вшиваться{}, // вшиваться в ткань rus_verbs:вшить{}, // вшить заплату в ткань rus_verbs:въедаться{}, // въедаться в мякоть rus_verbs:въезжать{}, // въезжать в гараж rus_verbs:въехать{}, // въехать в гараж rus_verbs:выиграть{}, // Коля выиграл в шахматы rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы rus_verbs:выкладывать{}, // выкладывать в общий доступ rus_verbs:выкладываться{}, // выкладываться в общий доступ rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет rus_verbs:вылезать{}, // вылезать в открытое пространство rus_verbs:вылезти{}, // вылезти в открытое пространство rus_verbs:выливать{}, // выливать в бутылку rus_verbs:выливаться{}, // выливаться в ёмкость rus_verbs:вылить{}, // вылить отходы в канализацию rus_verbs:вылиться{}, // Топливо вылилось в воду rus_verbs:выложить{}, // выложить в общий доступ rus_verbs:выпадать{}, // выпадать в осадок rus_verbs:выпрыгивать{}, // выпрыгивать в окно rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно rus_verbs:выродиться{}, // выродиться в жалкое подобие rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков rus_verbs:высеваться{}, // высеваться в землю rus_verbs:высеять{}, // высеять в землю rus_verbs:выслать{}, // выслать в страну постоянного пребывания rus_verbs:высморкаться{}, // высморкаться в платок rus_verbs:высморкнуться{}, // высморкнуться в платок rus_verbs:выстреливать{}, // выстреливать в цель rus_verbs:выстреливаться{}, // выстреливаться в цель rus_verbs:выстрелить{}, // выстрелить в цель rus_verbs:вытекать{}, // вытекать в озеро rus_verbs:вытечь{}, // вытечь в воду rus_verbs:смотреть{}, // смотреть в будущее rus_verbs:подняться{}, // подняться в лабораторию rus_verbs:послать{}, // послать в магазин rus_verbs:слать{}, // слать в неизвестность rus_verbs:добавить{}, // добавить в суп rus_verbs:пройти{}, // пройти в лабораторию rus_verbs:положить{}, // положить в ящик rus_verbs:прислать{}, // прислать в полицию rus_verbs:упасть{}, // упасть в пропасть инфинитив:писать{ aux stress="пис^ать" }, // писать в газету инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки глагол:писать{ aux stress="п^исать" }, глагол:писать{ aux stress="пис^ать" }, деепричастие:писая{}, прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету rus_verbs:собираться{}, // собираться в поход rus_verbs:звать{}, // звать в ресторан rus_verbs:направиться{}, // направиться в ресторан rus_verbs:отправиться{}, // отправиться в ресторан rus_verbs:поставить{}, // поставить в угол rus_verbs:целить{}, // целить в мишень rus_verbs:попасть{}, // попасть в переплет rus_verbs:ударить{}, // ударить в больное место rus_verbs:закричать{}, // закричать в микрофон rus_verbs:опустить{}, // опустить в воду rus_verbs:принести{}, // принести в дом бездомного щенка rus_verbs:отдать{}, // отдать в хорошие руки rus_verbs:ходить{}, // ходить в школу rus_verbs:уставиться{}, // уставиться в экран rus_verbs:приходить{}, // приходить в бешенство rus_verbs:махнуть{}, // махнуть в Италию rus_verbs:сунуть{}, // сунуть в замочную скважину rus_verbs:явиться{}, // явиться в расположение части rus_verbs:уехать{}, // уехать в город rus_verbs:целовать{}, // целовать в лобик rus_verbs:повести{}, // повести в бой rus_verbs:опуститься{}, // опуститься в кресло rus_verbs:передать{}, // передать в архив rus_verbs:побежать{}, // побежать в школу rus_verbs:стечь{}, // стечь в воду rus_verbs:уходить{}, // уходить добровольцем в армию rus_verbs:привести{}, // привести в дом rus_verbs:шагнуть{}, // шагнуть в неизвестность rus_verbs:собраться{}, // собраться в поход rus_verbs:заглянуть{}, // заглянуть в основу rus_verbs:поспешить{}, // поспешить в церковь rus_verbs:поцеловать{}, // поцеловать в лоб rus_verbs:перейти{}, // перейти в высшую лигу rus_verbs:поверить{}, // поверить в искренность rus_verbs:глянуть{}, // глянуть в оглавление rus_verbs:зайти{}, // зайти в кафетерий rus_verbs:подобрать{}, // подобрать в лесу rus_verbs:проходить{}, // проходить в помещение rus_verbs:глядеть{}, // глядеть в глаза rus_verbs:пригласить{}, // пригласить в театр rus_verbs:позвать{}, // позвать в класс rus_verbs:усесться{}, // усесться в кресло rus_verbs:поступить{}, // поступить в институт rus_verbs:лечь{}, // лечь в постель rus_verbs:поклониться{}, // поклониться в пояс rus_verbs:потянуться{}, // потянуться в лес rus_verbs:колоть{}, // колоть в ягодицу rus_verbs:присесть{}, // присесть в кресло rus_verbs:оглядеться{}, // оглядеться в зеркало rus_verbs:поглядеть{}, // поглядеть в зеркало rus_verbs:превратиться{}, // превратиться в лягушку rus_verbs:принимать{}, // принимать во внимание rus_verbs:звонить{}, // звонить в колокола rus_verbs:привезти{}, // привезти в гостиницу rus_verbs:рухнуть{}, // рухнуть в пропасть rus_verbs:пускать{}, // пускать в дело rus_verbs:отвести{}, // отвести в больницу rus_verbs:сойти{}, // сойти в ад rus_verbs:набрать{}, // набрать в команду rus_verbs:собрать{}, // собрать в кулак rus_verbs:двигаться{}, // двигаться в каюту rus_verbs:падать{}, // падать в область нуля rus_verbs:полезть{}, // полезть в драку rus_verbs:направить{}, // направить в стационар rus_verbs:приводить{}, // приводить в чувство rus_verbs:толкнуть{}, // толкнуть в бок rus_verbs:кинуться{}, // кинуться в драку rus_verbs:ткнуть{}, // ткнуть в глаз rus_verbs:заключить{}, // заключить в объятия rus_verbs:подниматься{}, // подниматься в небо rus_verbs:расти{}, // расти в глубину rus_verbs:налить{}, // налить в кружку rus_verbs:швырнуть{}, // швырнуть в бездну rus_verbs:прыгнуть{}, // прыгнуть в дверь rus_verbs:промолчать{}, // промолчать в тряпочку rus_verbs:садиться{}, // садиться в кресло rus_verbs:лить{}, // лить в кувшин rus_verbs:дослать{}, // дослать деталь в держатель rus_verbs:переслать{}, // переслать в обработчик rus_verbs:удалиться{}, // удалиться в совещательную комнату rus_verbs:разглядывать{}, // разглядывать в бинокль rus_verbs:повесить{}, // повесить в шкаф инфинитив:походить{ вид:соверш }, // походить в институт глагол:походить{ вид:соверш }, деепричастие:походив{}, // прилагательное:походивший{вид:соверш}, rus_verbs:помчаться{}, // помчаться в класс rus_verbs:свалиться{}, // свалиться в яму rus_verbs:сбежать{}, // сбежать в Англию rus_verbs:стрелять{}, // стрелять в цель rus_verbs:обращать{}, // обращать в свою веру rus_verbs:завести{}, // завести в дом rus_verbs:приобрести{}, // приобрести в рассрочку rus_verbs:сбросить{}, // сбросить в яму rus_verbs:устроиться{}, // устроиться в крупную корпорацию rus_verbs:погрузиться{}, // погрузиться в пучину rus_verbs:течь{}, // течь в канаву rus_verbs:произвести{}, // произвести в звание майора rus_verbs:метать{}, // метать в цель rus_verbs:пустить{}, // пустить в дело rus_verbs:полететь{}, // полететь в Европу rus_verbs:пропустить{}, // пропустить в здание rus_verbs:рвануть{}, // рвануть в отпуск rus_verbs:заходить{}, // заходить в каморку rus_verbs:нырнуть{}, // нырнуть в прорубь rus_verbs:рвануться{}, // рвануться в атаку rus_verbs:приподняться{}, // приподняться в воздух rus_verbs:превращаться{}, // превращаться в крупную величину rus_verbs:прокричать{}, // прокричать в ухо rus_verbs:записать{}, // записать в блокнот rus_verbs:забраться{}, // забраться в шкаф rus_verbs:приезжать{}, // приезжать в деревню rus_verbs:продать{}, // продать в рабство rus_verbs:проникнуть{}, // проникнуть в центр rus_verbs:устремиться{}, // устремиться в открытое море rus_verbs:посадить{}, // посадить в кресло rus_verbs:упереться{}, // упереться в пол rus_verbs:ринуться{}, // ринуться в буфет rus_verbs:отдавать{}, // отдавать в кадетское училище rus_verbs:отложить{}, // отложить в долгий ящик rus_verbs:убежать{}, // убежать в приют rus_verbs:оценить{}, // оценить в миллион долларов rus_verbs:поднимать{}, // поднимать в стратосферу rus_verbs:отослать{}, // отослать в квалификационную комиссию rus_verbs:отодвинуть{}, // отодвинуть в дальний угол rus_verbs:торопиться{}, // торопиться в школу rus_verbs:попадаться{}, // попадаться в руки rus_verbs:поразить{}, // поразить в самое сердце rus_verbs:доставить{}, // доставить в квартиру rus_verbs:заслать{}, // заслать в тыл rus_verbs:сослать{}, // сослать в изгнание rus_verbs:запустить{}, // запустить в космос rus_verbs:удариться{}, // удариться в запой rus_verbs:ударяться{}, // ударяться в крайность rus_verbs:шептать{}, // шептать в лицо rus_verbs:уронить{}, // уронить в унитаз rus_verbs:прорычать{}, // прорычать в микрофон rus_verbs:засунуть{}, // засунуть в глотку rus_verbs:плыть{}, // плыть в открытое море rus_verbs:перенести{}, // перенести в духовку rus_verbs:светить{}, // светить в лицо rus_verbs:мчаться{}, // мчаться в ремонт rus_verbs:стукнуть{}, // стукнуть в лоб rus_verbs:обрушиться{}, // обрушиться в котлован rus_verbs:поглядывать{}, // поглядывать в экран rus_verbs:уложить{}, // уложить в кроватку инфинитив:попадать{ вид:несоверш }, // попадать в черный список глагол:попадать{ вид:несоверш }, прилагательное:попадающий{ вид:несоверш }, прилагательное:попадавший{ вид:несоверш }, деепричастие:попадая{}, rus_verbs:провалиться{}, // провалиться в яму rus_verbs:жаловаться{}, // жаловаться в комиссию rus_verbs:опоздать{}, // опоздать в школу rus_verbs:посылать{}, // посылать в парикмахерскую rus_verbs:погнать{}, // погнать в хлев rus_verbs:поступать{}, // поступать в институт rus_verbs:усадить{}, // усадить в кресло rus_verbs:проиграть{}, // проиграть в рулетку rus_verbs:прилететь{}, // прилететь в страну rus_verbs:повалиться{}, // повалиться в траву rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ rus_verbs:лезть{}, // лезть в чужие дела rus_verbs:потащить{}, // потащить в суд rus_verbs:направляться{}, // направляться в порт rus_verbs:поползти{}, // поползти в другую сторону rus_verbs:пуститься{}, // пуститься в пляс rus_verbs:забиться{}, // забиться в нору rus_verbs:залезть{}, // залезть в конуру rus_verbs:сдать{}, // сдать в утиль rus_verbs:тронуться{}, // тронуться в путь rus_verbs:сыграть{}, // сыграть в шахматы rus_verbs:перевернуть{}, // перевернуть в более удобную позу rus_verbs:сжимать{}, // сжимать пальцы в кулак rus_verbs:подтолкнуть{}, // подтолкнуть в бок rus_verbs:отнести{}, // отнести животное в лечебницу rus_verbs:одеться{}, // одеться в зимнюю одежду rus_verbs:плюнуть{}, // плюнуть в колодец rus_verbs:передавать{}, // передавать в прокуратуру rus_verbs:отскочить{}, // отскочить в лоб rus_verbs:призвать{}, // призвать в армию rus_verbs:увезти{}, // увезти в деревню rus_verbs:улечься{}, // улечься в кроватку rus_verbs:отшатнуться{}, // отшатнуться в сторону rus_verbs:ложиться{}, // ложиться в постель rus_verbs:пролететь{}, // пролететь в конец rus_verbs:класть{}, // класть в сейф rus_verbs:доставлять{}, // доставлять в кабинет rus_verbs:приобретать{}, // приобретать в кредит rus_verbs:сводить{}, // сводить в театр rus_verbs:унести{}, // унести в могилу rus_verbs:покатиться{}, // покатиться в яму rus_verbs:сходить{}, // сходить в магазинчик rus_verbs:спустить{}, // спустить в канализацию rus_verbs:проникать{}, // проникать в сердцевину rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд rus_verbs:пожаловаться{}, // пожаловаться в администрацию rus_verbs:стучать{}, // стучать в металлическую дверь rus_verbs:тащить{}, // тащить в ремонт rus_verbs:заглядывать{}, // заглядывать в ответы rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена rus_verbs:увести{}, // увести в следующий кабинет rus_verbs:успевать{}, // успевать в школу rus_verbs:пробраться{}, // пробраться в собачью конуру rus_verbs:подавать{}, // подавать в суд rus_verbs:прибежать{}, // прибежать в конюшню rus_verbs:рассмотреть{}, // рассмотреть в микроскоп rus_verbs:пнуть{}, // пнуть в живот rus_verbs:завернуть{}, // завернуть в декоративную пленку rus_verbs:уезжать{}, // уезжать в деревню rus_verbs:привлекать{}, // привлекать в свои ряды rus_verbs:перебраться{}, // перебраться в прибрежный город rus_verbs:долить{}, // долить в коктейль rus_verbs:палить{}, // палить в нападающих rus_verbs:отобрать{}, // отобрать в коллекцию rus_verbs:улететь{}, // улететь в неизвестность rus_verbs:выглянуть{}, // выглянуть в окно rus_verbs:выглядывать{}, // выглядывать в окно rus_verbs:пробираться{}, // грабитель, пробирающийся в дом инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог глагол:написать{ aux stress="напис^ать"}, прилагательное:написавший{ aux stress="напис^авший"}, rus_verbs:свернуть{}, // свернуть в колечко инфинитив:сползать{ вид:несоверш }, // сползать в овраг глагол:сползать{ вид:несоверш }, прилагательное:сползающий{ вид:несоверш }, прилагательное:сползавший{ вид:несоверш }, rus_verbs:барабанить{}, // барабанить в дверь rus_verbs:дописывать{}, // дописывать в конец rus_verbs:меняться{}, // меняться в лучшую сторону rus_verbs:измениться{}, // измениться в лучшую сторону rus_verbs:изменяться{}, // изменяться в лучшую сторону rus_verbs:вписаться{}, // вписаться в поворот rus_verbs:вписываться{}, // вписываться в повороты rus_verbs:переработать{}, // переработать в удобрение rus_verbs:перерабатывать{}, // перерабатывать в удобрение rus_verbs:уползать{}, // уползать в тень rus_verbs:заползать{}, // заползать в нору rus_verbs:перепрятать{}, // перепрятать в укромное место rus_verbs:заталкивать{}, // заталкивать в вагон rus_verbs:преобразовывать{}, // преобразовывать в список инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список глагол:конвертировать{ вид:несоверш }, инфинитив:конвертировать{ вид:соверш }, глагол:конвертировать{ вид:соверш }, деепричастие:конвертировав{}, деепричастие:конвертируя{}, rus_verbs:изорвать{}, // Он изорвал газету в клочки. rus_verbs:выходить{}, // Окна выходят в сад. rus_verbs:говорить{}, // Он говорил в защиту своего отца. rus_verbs:вырастать{}, // Он вырастает в большого художника. rus_verbs:вывести{}, // Он вывел детей в сад. // инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш }, // глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли. // прилагательное:раненый{}, // Он был ранен в левую руку. // прилагательное:одетый{}, // Он был одет в толстое осеннее пальто. rus_verbs:бухнуться{}, // Он бухнулся в воду. rus_verbs:склонять{}, // склонять защиту в свою пользу rus_verbs:впиться{}, // Пиявка впилась в тело. rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы rus_verbs:сохранять{}, // сохранить данные в файл rus_verbs:собирать{}, // собирать игрушки в ящик rus_verbs:упаковывать{}, // упаковывать вещи в чемодан rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:стрельнуть{}, // стрельни в толпу! rus_verbs:пулять{}, // пуляй в толпу rus_verbs:пульнуть{}, // пульни в толпу rus_verbs:становиться{}, // Становитесь в очередь. rus_verbs:вписать{}, // Юля вписала свое имя в список. rus_verbs:вписывать{}, // Мы вписывали свои имена в список прилагательное:видный{}, // Планета Марс видна в обычный бинокль rus_verbs:пойти{}, // Девочка рано пошла в школу rus_verbs:отойти{}, // Эти обычаи отошли в историю. rus_verbs:бить{}, // Холодный ветер бил ему в лицо. rus_verbs:входить{}, // Это входит в его обязанности. rus_verbs:принять{}, // меня приняли в пионеры rus_verbs:уйти{}, // Правительство РФ ушло в отставку rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году. rus_verbs:посвятить{}, // Я посвятил друга в свою тайну. инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза. rus_verbs:идти{}, // Я иду гулять в парк. rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт. rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей. rus_verbs:везти{}, // Учитель везёт детей в лагерь. rus_verbs:качать{}, // Судно качает во все стороны. rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами. rus_verbs:связать{}, // Свяжите свои вещи в узелок. rus_verbs:пронести{}, // Пронесите стол в дверь. rus_verbs:вынести{}, // Надо вынести примечания в конец. rus_verbs:устроить{}, // Она устроила сына в школу. rus_verbs:угодить{}, // Она угодила головой в дверь. rus_verbs:отвернуться{}, // Она резко отвернулась в сторону. rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль. rus_verbs:обратить{}, // Война обратила город в развалины. rus_verbs:сойтись{}, // Мы сошлись в школьные годы. rus_verbs:приехать{}, // Мы приехали в положенный час. rus_verbs:встать{}, // Дети встали в круг. rus_verbs:впасть{}, // Из-за болезни он впал в нужду. rus_verbs:придти{}, // придти в упадок rus_verbs:заявить{}, // Надо заявить в милицию о краже. rus_verbs:заявлять{}, // заявлять в полицию rus_verbs:ехать{}, // Мы будем ехать в Орёл rus_verbs:окрашиваться{}, // окрашиваться в красный цвет rus_verbs:решить{}, // Дело решено в пользу истца. rus_verbs:сесть{}, // Она села в кресло rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало. rus_verbs:влезать{}, // он влезает в мою квартирку rus_verbs:попасться{}, // в мою ловушку попалась мышь rus_verbs:лететь{}, // Мы летим в Орёл ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень ГЛ_ИНФ(взять), // Коля взял в руку камень ГЛ_ИНФ(поехать), // поехать в круиз ГЛ_ИНФ(подать), // подать в отставку инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море ГЛ_ИНФ(постучать) // постучать в дверь } // Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems fact гл_предл { if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } } then return true } #endregion Винительный // Все остальные варианты по умолчанию запрещаем. fact гл_предл { if context { * предлог:в{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:в{} * } then return false,-5 } #endregion Предлог_В #region Предлог_НА // ------------------- С ПРЕДЛОГОМ 'НА' --------------------------- #region ПРЕДЛОЖНЫЙ // НА+предложный падеж: // ЛЕЖАТЬ НА СТОЛЕ #region VerbList wordentry_set Гл_НА_Предл= { rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ) rus_verbs:ПРОСТУПИТЬ{}, // rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ) rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ) rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив) rus_verbs:ЗАМИРАТЬ{}, // rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ) rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ) rus_verbs:УПОЛЗАТЬ{}, // rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ) rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ) rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ) rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ) rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ) rus_verbs:искриться{}, rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ) rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ) rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ) rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ) rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ) rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ) rus_verbs:отвести{}, // отвести душу на людях rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра rus_verbs:сойтись{}, rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ) rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ) rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ) глагол:ДОСТИЧЬ{}, инфинитив:ДОСТИЧЬ{}, rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте rus_verbs:РАСКЛАДЫВАТЬ{}, rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ) rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ) rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ) rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ) rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ) rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ) rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта rus_verbs:подпрыгивать{}, rus_verbs:высветиться{}, // на компьютере высветится твоя подпись rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА) rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл) rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл) rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА) rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл) rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл) rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл) rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл) rus_verbs:ОТТОЧИТЬ{}, rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА) rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл) инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл) глагол:НАХОДИТЬСЯ{ вид:несоверш }, прилагательное:находившийся{ вид:несоверш }, прилагательное:находящийся{ вид:несоверш }, деепричастие:находясь{}, rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл) rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА) rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА) rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл) rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА) rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл) rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА) rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА) rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА) rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА) rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА) rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА) rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл) rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА) rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА) rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА) rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА) rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА) rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА) rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл) rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл) rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на) rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к) rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на) глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте) деепричастие:вычитав{}, rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на) rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере rus_verbs:развалиться{}, // Антонио развалился на диване rus_verbs:улечься{}, // Антонио улегся на полу rus_verbs:зарубить{}, // Заруби себе на носу. rus_verbs:ценить{}, // Его ценят на заводе. rus_verbs:вернуться{}, // Отец вернулся на закате. rus_verbs:шить{}, // Вы умеете шить на машинке? rus_verbs:бить{}, // Скот бьют на бойне. rus_verbs:выехать{}, // Мы выехали на рассвете. rus_verbs:валяться{}, // На полу валяется бумага. rus_verbs:разложить{}, // она разложила полотенце на песке rus_verbs:заниматься{}, // я занимаюсь на тренажере rus_verbs:позаниматься{}, rus_verbs:порхать{}, // порхать на лугу rus_verbs:пресекать{}, // пресекать на корню rus_verbs:изъясняться{}, // изъясняться на непонятном языке rus_verbs:развесить{}, // развесить на столбах rus_verbs:обрасти{}, // обрасти на южной части rus_verbs:откладываться{}, // откладываться на стенках артерий rus_verbs:уносить{}, // уносить на носилках rus_verbs:проплыть{}, // проплыть на плоту rus_verbs:подъезжать{}, // подъезжать на повозках rus_verbs:пульсировать{}, // пульсировать на лбу rus_verbs:рассесться{}, // птицы расселись на ветках rus_verbs:застопориться{}, // застопориться на первом пункте rus_verbs:изловить{}, // изловить на окраинах rus_verbs:покататься{}, // покататься на машинках rus_verbs:залопотать{}, // залопотать на неизвестном языке rus_verbs:растягивать{}, // растягивать на станке rus_verbs:поделывать{}, // поделывать на пляже rus_verbs:подстеречь{}, // подстеречь на площадке rus_verbs:проектировать{}, // проектировать на компьютере rus_verbs:притулиться{}, // притулиться на кушетке rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище rus_verbs:пострелять{}, // пострелять на испытательном полигоне rus_verbs:засиживаться{}, // засиживаться на работе rus_verbs:нежиться{}, // нежиться на солнышке rus_verbs:притомиться{}, // притомиться на рабочем месте rus_verbs:поселяться{}, // поселяться на чердаке rus_verbs:потягиваться{}, // потягиваться на земле rus_verbs:отлеживаться{}, // отлеживаться на койке rus_verbs:протаранить{}, // протаранить на танке rus_verbs:гарцевать{}, // гарцевать на коне rus_verbs:облупиться{}, // облупиться на носу rus_verbs:оговорить{}, // оговорить на собеседовании rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте rus_verbs:отпечатать{}, // отпечатать на картоне rus_verbs:сэкономить{}, // сэкономить на мелочах rus_verbs:покатать{}, // покатать на пони rus_verbs:колесить{}, // колесить на старой машине rus_verbs:понастроить{}, // понастроить на участках rus_verbs:поджарить{}, // поджарить на костре rus_verbs:узнаваться{}, // узнаваться на фотографии rus_verbs:отощать{}, // отощать на казенных харчах rus_verbs:редеть{}, // редеть на макушке rus_verbs:оглашать{}, // оглашать на общем собрании rus_verbs:лопотать{}, // лопотать на иврите rus_verbs:пригреть{}, // пригреть на груди rus_verbs:консультироваться{}, // консультироваться на форуме rus_verbs:приноситься{}, // приноситься на одежде rus_verbs:сушиться{}, // сушиться на балконе rus_verbs:наследить{}, // наследить на полу rus_verbs:нагреться{}, // нагреться на солнце rus_verbs:рыбачить{}, // рыбачить на озере rus_verbs:прокатить{}, // прокатить на выборах rus_verbs:запинаться{}, // запинаться на ровном месте rus_verbs:отрубиться{}, // отрубиться на мягкой подушке rus_verbs:заморозить{}, // заморозить на улице rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе rus_verbs:просохнуть{}, // просохнуть на батарее rus_verbs:развозить{}, // развозить на велосипеде rus_verbs:прикорнуть{}, // прикорнуть на диванчике rus_verbs:отпечататься{}, // отпечататься на коже rus_verbs:выявлять{}, // выявлять на таможне rus_verbs:расставлять{}, // расставлять на башнях rus_verbs:прокрутить{}, // прокрутить на пальце rus_verbs:умываться{}, // умываться на улице rus_verbs:пересказывать{}, // пересказывать на страницах романа rus_verbs:удалять{}, // удалять на пуховике rus_verbs:хозяйничать{}, // хозяйничать на складе rus_verbs:оперировать{}, // оперировать на поле боя rus_verbs:поносить{}, // поносить на голове rus_verbs:замурлыкать{}, // замурлыкать на коленях rus_verbs:передвигать{}, // передвигать на тележке rus_verbs:прочертить{}, // прочертить на земле rus_verbs:колдовать{}, // колдовать на кухне rus_verbs:отвозить{}, // отвозить на казенном транспорте rus_verbs:трахать{}, // трахать на природе rus_verbs:мастерить{}, // мастерить на кухне rus_verbs:ремонтировать{}, // ремонтировать на коленке rus_verbs:развезти{}, // развезти на велосипеде rus_verbs:робеть{}, // робеть на сцене инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш }, деепричастие:реализовав{}, деепричастие:реализуя{}, rus_verbs:покаяться{}, // покаяться на смертном одре rus_verbs:специализироваться{}, // специализироваться на тестировании rus_verbs:попрыгать{}, // попрыгать на батуте rus_verbs:переписывать{}, // переписывать на столе rus_verbs:расписывать{}, // расписывать на доске rus_verbs:зажимать{}, // зажимать на запястье rus_verbs:практиковаться{}, // практиковаться на мышах rus_verbs:уединиться{}, // уединиться на чердаке rus_verbs:подохнуть{}, // подохнуть на чужбине rus_verbs:приподниматься{}, // приподниматься на руках rus_verbs:уродиться{}, // уродиться на полях rus_verbs:продолжиться{}, // продолжиться на улице rus_verbs:посапывать{}, // посапывать на диване rus_verbs:ободрать{}, // ободрать на спине rus_verbs:скрючиться{}, // скрючиться на песке rus_verbs:тормознуть{}, // тормознуть на перекрестке rus_verbs:лютовать{}, // лютовать на хуторе rus_verbs:зарегистрировать{}, // зарегистрировать на сайте rus_verbs:переждать{}, // переждать на вершине холма rus_verbs:доминировать{}, // доминировать на территории rus_verbs:публиковать{}, // публиковать на сайте rus_verbs:морщить{}, // морщить на лбу rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном rus_verbs:подрабатывать{}, // подрабатывать на рынке rus_verbs:репетировать{}, // репетировать на заднем дворе rus_verbs:подвернуть{}, // подвернуть на брусчатке rus_verbs:зашелестеть{}, // зашелестеть на ветру rus_verbs:расчесывать{}, // расчесывать на спине rus_verbs:одевать{}, // одевать на рынке rus_verbs:испечь{}, // испечь на углях rus_verbs:сбрить{}, // сбрить на затылке rus_verbs:согреться{}, // согреться на печке rus_verbs:замаячить{}, // замаячить на горизонте rus_verbs:пересчитывать{}, // пересчитывать на пальцах rus_verbs:галдеть{}, // галдеть на крыльце rus_verbs:переплыть{}, // переплыть на плоту rus_verbs:передохнуть{}, // передохнуть на скамейке rus_verbs:прижиться{}, // прижиться на ферме rus_verbs:переправляться{}, // переправляться на плотах rus_verbs:накупить{}, // накупить на блошином рынке rus_verbs:проторчать{}, // проторчать на виду rus_verbs:мокнуть{}, // мокнуть на улице rus_verbs:застукать{}, // застукать на камбузе rus_verbs:завязывать{}, // завязывать на ботинках rus_verbs:повисать{}, // повисать на ветке rus_verbs:подвизаться{}, // подвизаться на государственной службе rus_verbs:кормиться{}, // кормиться на болоте rus_verbs:покурить{}, // покурить на улице rus_verbs:зимовать{}, // зимовать на болотах rus_verbs:застегивать{}, // застегивать на гимнастерке rus_verbs:поигрывать{}, // поигрывать на гитаре rus_verbs:погореть{}, // погореть на махинациях с землей rus_verbs:кувыркаться{}, // кувыркаться на батуте rus_verbs:похрапывать{}, // похрапывать на диване rus_verbs:пригревать{}, // пригревать на груди rus_verbs:завязнуть{}, // завязнуть на болоте rus_verbs:шастать{}, // шастать на втором этаже rus_verbs:заночевать{}, // заночевать на сеновале rus_verbs:отсиживаться{}, // отсиживаться на чердаке rus_verbs:мчать{}, // мчать на байке rus_verbs:сгнить{}, // сгнить на урановых рудниках rus_verbs:тренировать{}, // тренировать на манекенах rus_verbs:повеселиться{}, // повеселиться на празднике rus_verbs:измучиться{}, // измучиться на болоте rus_verbs:увянуть{}, // увянуть на подоконнике rus_verbs:раскрутить{}, // раскрутить на оси rus_verbs:выцвести{}, // выцвести на солнечном свету rus_verbs:изготовлять{}, // изготовлять на коленке rus_verbs:гнездиться{}, // гнездиться на вершине дерева rus_verbs:разогнаться{}, // разогнаться на мотоцикле rus_verbs:излагаться{}, // излагаться на страницах доклада rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге rus_verbs:расчесать{}, // расчесать на макушке rus_verbs:плавиться{}, // плавиться на солнце rus_verbs:редактировать{}, // редактировать на ноутбуке rus_verbs:подскакивать{}, // подскакивать на месте rus_verbs:покупаться{}, // покупаться на рынке rus_verbs:промышлять{}, // промышлять на мелководье rus_verbs:приобретаться{}, // приобретаться на распродажах rus_verbs:наигрывать{}, // наигрывать на банджо rus_verbs:маневрировать{}, // маневрировать на флангах rus_verbs:запечатлеться{}, // запечатлеться на записях камер rus_verbs:укрывать{}, // укрывать на чердаке rus_verbs:подорваться{}, // подорваться на фугасе rus_verbs:закрепиться{}, // закрепиться на занятых позициях rus_verbs:громыхать{}, // громыхать на кухне инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу деепричастие:подвигавшись{}, rus_verbs:добываться{}, // добываться на территории Анголы rus_verbs:приплясывать{}, // приплясывать на сцене rus_verbs:доживать{}, // доживать на больничной койке rus_verbs:отпраздновать{}, // отпраздновать на работе rus_verbs:сгубить{}, // сгубить на корню rus_verbs:схоронить{}, // схоронить на кладбище rus_verbs:тускнеть{}, // тускнеть на солнце rus_verbs:скопить{}, // скопить на счету rus_verbs:помыть{}, // помыть на своем этаже rus_verbs:пороть{}, // пороть на конюшне rus_verbs:наличествовать{}, // наличествовать на складе rus_verbs:нащупывать{}, // нащупывать на полке rus_verbs:змеиться{}, // змеиться на дне rus_verbs:пожелтеть{}, // пожелтеть на солнце rus_verbs:заостриться{}, // заостриться на конце rus_verbs:свезти{}, // свезти на поле rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре rus_verbs:подкрутить{}, // подкрутить на приборной панели rus_verbs:рубиться{}, // рубиться на мечах rus_verbs:сиживать{}, // сиживать на крыльце rus_verbs:тараторить{}, // тараторить на иностранном языке rus_verbs:теплеть{}, // теплеть на сердце rus_verbs:покачаться{}, // покачаться на ветке rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче rus_verbs:развязывать{}, // развязывать на ботинках rus_verbs:подвозить{}, // подвозить на мотороллере rus_verbs:вышивать{}, // вышивать на рубашке rus_verbs:скупать{}, // скупать на открытом рынке rus_verbs:оформлять{}, // оформлять на встрече rus_verbs:распускаться{}, // распускаться на клумбах rus_verbs:прогореть{}, // прогореть на спекуляциях rus_verbs:приползти{}, // приползти на коленях rus_verbs:загореть{}, // загореть на пляже rus_verbs:остудить{}, // остудить на балконе rus_verbs:нарвать{}, // нарвать на поляне rus_verbs:издохнуть{}, // издохнуть на болоте rus_verbs:разгружать{}, // разгружать на дороге rus_verbs:произрастать{}, // произрастать на болотах rus_verbs:разуться{}, // разуться на коврике rus_verbs:сооружать{}, // сооружать на площади rus_verbs:зачитывать{}, // зачитывать на митинге rus_verbs:уместиться{}, // уместиться на ладони rus_verbs:закупить{}, // закупить на рынке rus_verbs:горланить{}, // горланить на улице rus_verbs:экономить{}, // экономить на спичках rus_verbs:исправлять{}, // исправлять на доске rus_verbs:расслабляться{}, // расслабляться на лежаке rus_verbs:скапливаться{}, // скапливаться на крыше rus_verbs:сплетничать{}, // сплетничать на скамеечке rus_verbs:отъезжать{}, // отъезжать на лимузине rus_verbs:отчитывать{}, // отчитывать на собрании rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке rus_verbs:потчевать{}, // потчевать на лаврах rus_verbs:окопаться{}, // окопаться на окраине rus_verbs:загорать{}, // загорать на пляже rus_verbs:обгореть{}, // обгореть на солнце rus_verbs:распознавать{}, // распознавать на фотографии rus_verbs:заплетаться{}, // заплетаться на макушке rus_verbs:перегреться{}, // перегреться на жаре rus_verbs:подметать{}, // подметать на крыльце rus_verbs:нарисоваться{}, // нарисоваться на горизонте rus_verbs:проскакивать{}, // проскакивать на экране rus_verbs:попивать{}, // попивать на балконе чай rus_verbs:отплывать{}, // отплывать на лодке rus_verbs:чирикать{}, // чирикать на ветках rus_verbs:скупить{}, // скупить на оптовых базах rus_verbs:наколоть{}, // наколоть на коже картинку rus_verbs:созревать{}, // созревать на ветке rus_verbs:проколоться{}, // проколоться на мелочи rus_verbs:крутнуться{}, // крутнуться на заднем колесе rus_verbs:переночевать{}, // переночевать на постоялом дворе rus_verbs:концентрироваться{}, // концентрироваться на фильтре rus_verbs:одичать{}, // одичать на хуторе rus_verbs:спасаться{}, // спасаются на лодке rus_verbs:доказываться{}, // доказываться на страницах книги rus_verbs:познаваться{}, // познаваться на ринге rus_verbs:замыкаться{}, // замыкаться на металлическом предмете rus_verbs:заприметить{}, // заприметить на пригорке rus_verbs:продержать{}, // продержать на морозе rus_verbs:форсировать{}, // форсировать на плотах rus_verbs:сохнуть{}, // сохнуть на солнце rus_verbs:выявить{}, // выявить на поверхности rus_verbs:заседать{}, // заседать на кафедре rus_verbs:расплачиваться{}, // расплачиваться на выходе rus_verbs:светлеть{}, // светлеть на горизонте rus_verbs:залепетать{}, // залепетать на незнакомом языке rus_verbs:подсчитывать{}, // подсчитывать на пальцах rus_verbs:зарыть{}, // зарыть на пустыре rus_verbs:сформироваться{}, // сформироваться на месте rus_verbs:развертываться{}, // развертываться на площадке rus_verbs:набивать{}, // набивать на манекенах rus_verbs:замерзать{}, // замерзать на ветру rus_verbs:схватывать{}, // схватывать на лету rus_verbs:перевестись{}, // перевестись на Руси rus_verbs:смешивать{}, // смешивать на блюдце rus_verbs:прождать{}, // прождать на входе rus_verbs:мерзнуть{}, // мерзнуть на ветру rus_verbs:растирать{}, // растирать на коже rus_verbs:переспать{}, // переспал на сеновале rus_verbs:рассекать{}, // рассекать на скутере rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне rus_verbs:дрыхнуть{}, // дрыхнуть на диване rus_verbs:распять{}, // распять на кресте rus_verbs:запечься{}, // запечься на костре rus_verbs:застилать{}, // застилать на балконе rus_verbs:сыскаться{}, // сыскаться на огороде rus_verbs:разориться{}, // разориться на продаже спичек rus_verbs:переделать{}, // переделать на станке rus_verbs:разъяснять{}, // разъяснять на страницах газеты rus_verbs:поседеть{}, // поседеть на висках rus_verbs:протащить{}, // протащить на спине rus_verbs:осуществиться{}, // осуществиться на деле rus_verbs:селиться{}, // селиться на окраине rus_verbs:оплачивать{}, // оплачивать на первой кассе rus_verbs:переворачивать{}, // переворачивать на сковородке rus_verbs:упражняться{}, // упражняться на батуте rus_verbs:испробовать{}, // испробовать на себе rus_verbs:разгладиться{}, // разгладиться на спине rus_verbs:рисоваться{}, // рисоваться на стекле rus_verbs:продрогнуть{}, // продрогнуть на морозе rus_verbs:пометить{}, // пометить на доске rus_verbs:приютить{}, // приютить на чердаке rus_verbs:избирать{}, // избирать на первых свободных выборах rus_verbs:затеваться{}, // затеваться на матче rus_verbs:уплывать{}, // уплывать на катере rus_verbs:замерцать{}, // замерцать на рекламном щите rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне rus_verbs:запираться{}, // запираться на чердаке rus_verbs:загубить{}, // загубить на корню rus_verbs:развеяться{}, // развеяться на природе rus_verbs:съезжаться{}, // съезжаться на лимузинах rus_verbs:потанцевать{}, // потанцевать на могиле rus_verbs:дохнуть{}, // дохнуть на солнце rus_verbs:припарковаться{}, // припарковаться на газоне rus_verbs:отхватить{}, // отхватить на распродаже rus_verbs:остывать{}, // остывать на улице rus_verbs:переваривать{}, // переваривать на высокой ветке rus_verbs:подвесить{}, // подвесить на веревке rus_verbs:хвастать{}, // хвастать на работе rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая rus_verbs:разлечься{}, // разлечься на полу rus_verbs:очертить{}, // очертить на полу rus_verbs:председательствовать{}, // председательствовать на собрании rus_verbs:сконфузиться{}, // сконфузиться на сцене rus_verbs:выявляться{}, // выявляться на ринге rus_verbs:крутануться{}, // крутануться на заднем колесе rus_verbs:караулить{}, // караулить на входе rus_verbs:перечислять{}, // перечислять на пальцах rus_verbs:обрабатывать{}, // обрабатывать на станке rus_verbs:настигать{}, // настигать на берегу rus_verbs:разгуливать{}, // разгуливать на берегу rus_verbs:насиловать{}, // насиловать на пляже rus_verbs:поредеть{}, // поредеть на макушке rus_verbs:учитывать{}, // учитывать на балансе rus_verbs:зарождаться{}, // зарождаться на большой глубине rus_verbs:распространять{}, // распространять на сайтах rus_verbs:пировать{}, // пировать на вершине холма rus_verbs:начертать{}, // начертать на стене rus_verbs:расцветать{}, // расцветать на подоконнике rus_verbs:умнеть{}, // умнеть на глазах rus_verbs:царствовать{}, // царствовать на окраине rus_verbs:закрутиться{}, // закрутиться на работе rus_verbs:отработать{}, // отработать на шахте rus_verbs:полечь{}, // полечь на поле брани rus_verbs:щебетать{}, // щебетать на ветке rus_verbs:подчеркиваться{}, // подчеркиваться на сайте rus_verbs:посеять{}, // посеять на другом поле rus_verbs:замечаться{}, // замечаться на пастбище rus_verbs:просчитать{}, // просчитать на пальцах rus_verbs:голосовать{}, // голосовать на трассе rus_verbs:маяться{}, // маяться на пляже rus_verbs:сколотить{}, // сколотить на службе rus_verbs:обретаться{}, // обретаться на чужбине rus_verbs:обливаться{}, // обливаться на улице rus_verbs:катать{}, // катать на лошадке rus_verbs:припрятать{}, // припрятать на теле rus_verbs:запаниковать{}, // запаниковать на экзамене инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете деепричастие:слетав{}, rus_verbs:срубить{}, // срубить денег на спекуляциях rus_verbs:зажигаться{}, // зажигаться на улице rus_verbs:жарить{}, // жарить на углях rus_verbs:накапливаться{}, // накапливаться на счету rus_verbs:распуститься{}, // распуститься на грядке rus_verbs:рассаживаться{}, // рассаживаться на местах rus_verbs:странствовать{}, // странствовать на лошади rus_verbs:осматриваться{}, // осматриваться на месте rus_verbs:разворачивать{}, // разворачивать на завоеванной территории rus_verbs:согревать{}, // согревать на вершине горы rus_verbs:заскучать{}, // заскучать на вахте rus_verbs:перекусить{}, // перекусить на бегу rus_verbs:приплыть{}, // приплыть на тримаране rus_verbs:зажигать{}, // зажигать на танцах rus_verbs:закопать{}, // закопать на поляне rus_verbs:стирать{}, // стирать на берегу rus_verbs:подстерегать{}, // подстерегать на подходе rus_verbs:погулять{}, // погулять на свадьбе rus_verbs:огласить{}, // огласить на митинге rus_verbs:разбогатеть{}, // разбогатеть на прииске rus_verbs:грохотать{}, // грохотать на чердаке rus_verbs:расположить{}, // расположить на границе rus_verbs:реализоваться{}, // реализоваться на новой работе rus_verbs:застывать{}, // застывать на морозе rus_verbs:запечатлеть{}, // запечатлеть на пленке rus_verbs:тренироваться{}, // тренироваться на манекене rus_verbs:поспорить{}, // поспорить на совещании rus_verbs:затягивать{}, // затягивать на поясе rus_verbs:зиждиться{}, // зиждиться на твердой основе rus_verbs:построиться{}, // построиться на песке rus_verbs:надрываться{}, // надрываться на работе rus_verbs:закипать{}, // закипать на плите rus_verbs:затонуть{}, // затонуть на мелководье rus_verbs:побыть{}, // побыть на фазенде rus_verbs:сгорать{}, // сгорать на солнце инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице деепричастие:пописав{ aux stress="поп^исав" }, rus_verbs:подраться{}, // подраться на сцене rus_verbs:заправить{}, // заправить на последней заправке rus_verbs:обозначаться{}, // обозначаться на карте rus_verbs:просиживать{}, // просиживать на берегу rus_verbs:начертить{}, // начертить на листке rus_verbs:тормозить{}, // тормозить на льду rus_verbs:затевать{}, // затевать на космической базе rus_verbs:задерживать{}, // задерживать на таможне rus_verbs:прилетать{}, // прилетать на частном самолете rus_verbs:полулежать{}, // полулежать на травке rus_verbs:ерзать{}, // ерзать на табуретке rus_verbs:покопаться{}, // покопаться на складе rus_verbs:подвезти{}, // подвезти на машине rus_verbs:полежать{}, // полежать на водном матрасе rus_verbs:стыть{}, // стыть на улице rus_verbs:стынуть{}, // стынуть на улице rus_verbs:скреститься{}, // скреститься на груди rus_verbs:припарковать{}, // припарковать на стоянке rus_verbs:здороваться{}, // здороваться на кафедре rus_verbs:нацарапать{}, // нацарапать на парте rus_verbs:откопать{}, // откопать на поляне rus_verbs:смастерить{}, // смастерить на коленках rus_verbs:довезти{}, // довезти на машине rus_verbs:избивать{}, // избивать на крыше rus_verbs:сварить{}, // сварить на костре rus_verbs:истребить{}, // истребить на корню rus_verbs:раскопать{}, // раскопать на болоте rus_verbs:попить{}, // попить на кухне rus_verbs:заправлять{}, // заправлять на базе rus_verbs:кушать{}, // кушать на кухне rus_verbs:замолкать{}, // замолкать на половине фразы rus_verbs:измеряться{}, // измеряться на весах rus_verbs:сбываться{}, // сбываться на самом деле rus_verbs:изображаться{}, // изображается на сцене rus_verbs:фиксировать{}, // фиксировать на данной высоте rus_verbs:ослаблять{}, // ослаблять на шее rus_verbs:зреть{}, // зреть на грядке rus_verbs:зеленеть{}, // зеленеть на грядке rus_verbs:критиковать{}, // критиковать на страницах газеты rus_verbs:облететь{}, // облететь на самолете rus_verbs:заразиться{}, // заразиться на работе rus_verbs:рассеять{}, // рассеять на территории rus_verbs:печься{}, // печься на костре rus_verbs:поспать{}, // поспать на земле rus_verbs:сплетаться{}, // сплетаться на макушке rus_verbs:удерживаться{}, // удерживаться на расстоянии rus_verbs:помешаться{}, // помешаться на чистоте rus_verbs:ликвидировать{}, // ликвидировать на полигоне rus_verbs:проваляться{}, // проваляться на диване rus_verbs:лечиться{}, // лечиться на дому rus_verbs:обработать{}, // обработать на станке rus_verbs:защелкнуть{}, // защелкнуть на руках rus_verbs:разносить{}, // разносить на одежде rus_verbs:чесать{}, // чесать на груди rus_verbs:наладить{}, // наладить на конвейере выпуск rus_verbs:отряхнуться{}, // отряхнуться на улице rus_verbs:разыгрываться{}, // разыгрываться на скачках rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях rus_verbs:греться{}, // греться на вокзале rus_verbs:засидеться{}, // засидеться на одном месте rus_verbs:материализоваться{}, // материализоваться на границе rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин rus_verbs:перевозить{}, // перевозить на платформе rus_verbs:поиграть{}, // поиграть на скрипке rus_verbs:потоптаться{}, // потоптаться на одном месте rus_verbs:переправиться{}, // переправиться на плоту rus_verbs:забрезжить{}, // забрезжить на горизонте rus_verbs:завывать{}, // завывать на опушке rus_verbs:заваривать{}, // заваривать на кухоньке rus_verbs:перемещаться{}, // перемещаться на спасательном плоту инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке rus_verbs:праздновать{}, // праздновать на улицах rus_verbs:обучить{}, // обучить на корте rus_verbs:орудовать{}, // орудовать на складе rus_verbs:подрасти{}, // подрасти на глядке rus_verbs:шелестеть{}, // шелестеть на ветру rus_verbs:раздеваться{}, // раздеваться на публике rus_verbs:пообедать{}, // пообедать на газоне rus_verbs:жрать{}, // жрать на помойке rus_verbs:исполняться{}, // исполняться на флейте rus_verbs:похолодать{}, // похолодать на улице rus_verbs:гнить{}, // гнить на каторге rus_verbs:прослушать{}, // прослушать на концерте rus_verbs:совещаться{}, // совещаться на заседании rus_verbs:покачивать{}, // покачивать на волнах rus_verbs:отсидеть{}, // отсидеть на гаупвахте rus_verbs:формировать{}, // формировать на секретной базе rus_verbs:захрапеть{}, // захрапеть на кровати rus_verbs:объехать{}, // объехать на попутке rus_verbs:поселить{}, // поселить на верхних этажах rus_verbs:заворочаться{}, // заворочаться на сене rus_verbs:напрятать{}, // напрятать на теле rus_verbs:очухаться{}, // очухаться на земле rus_verbs:полистать{}, // полистать на досуге rus_verbs:завертеть{}, // завертеть на шесте rus_verbs:печатать{}, // печатать на ноуте rus_verbs:отыскаться{}, // отыскаться на складе rus_verbs:зафиксировать{}, // зафиксировать на пленке rus_verbs:расстилаться{}, // расстилаться на столе rus_verbs:заместить{}, // заместить на посту rus_verbs:угасать{}, // угасать на неуправляемом корабле rus_verbs:сразить{}, // сразить на ринге rus_verbs:расплываться{}, // расплываться на жаре rus_verbs:сосчитать{}, // сосчитать на пальцах rus_verbs:сгуститься{}, // сгуститься на небольшой высоте rus_verbs:цитировать{}, // цитировать на плите rus_verbs:ориентироваться{}, // ориентироваться на местности rus_verbs:расширить{}, // расширить на другом конце rus_verbs:обтереть{}, // обтереть на стоянке rus_verbs:подстрелить{}, // подстрелить на охоте rus_verbs:растереть{}, // растереть на твердой поверхности rus_verbs:подавлять{}, // подавлять на первом этапе rus_verbs:смешиваться{}, // смешиваться на поверхности // инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте // деепричастие:вычитав{}, rus_verbs:сократиться{}, // сократиться на втором этапе rus_verbs:занервничать{}, // занервничать на экзамене rus_verbs:соприкоснуться{}, // соприкоснуться на трассе rus_verbs:обозначить{}, // обозначить на плане rus_verbs:обучаться{}, // обучаться на производстве rus_verbs:снизиться{}, // снизиться на большой высоте rus_verbs:простудиться{}, // простудиться на ветру rus_verbs:поддерживаться{}, // поддерживается на встрече rus_verbs:уплыть{}, // уплыть на лодочке rus_verbs:резвиться{}, // резвиться на песочке rus_verbs:поерзать{}, // поерзать на скамеечке rus_verbs:похвастаться{}, // похвастаться на встрече rus_verbs:знакомиться{}, // знакомиться на уроке rus_verbs:проплывать{}, // проплывать на катере rus_verbs:засесть{}, // засесть на чердаке rus_verbs:подцепить{}, // подцепить на дискотеке rus_verbs:обыскать{}, // обыскать на входе rus_verbs:оправдаться{}, // оправдаться на суде rus_verbs:раскрываться{}, // раскрываться на сцене rus_verbs:одеваться{}, // одеваться на вещевом рынке rus_verbs:засветиться{}, // засветиться на фотографиях rus_verbs:употребляться{}, // употребляться на птицефабриках rus_verbs:грабить{}, // грабить на пустыре rus_verbs:гонять{}, // гонять на повышенных оборотах rus_verbs:развеваться{}, // развеваться на древке rus_verbs:основываться{}, // основываться на безусловных фактах rus_verbs:допрашивать{}, // допрашивать на базе rus_verbs:проработать{}, // проработать на стройке rus_verbs:сосредоточить{}, // сосредоточить на месте rus_verbs:сочинять{}, // сочинять на ходу rus_verbs:ползать{}, // ползать на камне rus_verbs:раскинуться{}, // раскинуться на пустыре rus_verbs:уставать{}, // уставать на работе rus_verbs:укрепить{}, // укрепить на конце rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь rus_verbs:одобрять{}, // одобрять на словах rus_verbs:приговорить{}, // приговорить на заседании тройки rus_verbs:чернеть{}, // чернеть на свету rus_verbs:гнуть{}, // гнуть на станке rus_verbs:размещаться{}, // размещаться на бирже rus_verbs:соорудить{}, // соорудить на даче rus_verbs:пастись{}, // пастись на лугу rus_verbs:формироваться{}, // формироваться на дне rus_verbs:таить{}, // таить на дне rus_verbs:приостановиться{}, // приостановиться на середине rus_verbs:топтаться{}, // топтаться на месте rus_verbs:громить{}, // громить на подступах rus_verbs:вычислить{}, // вычислить на бумажке rus_verbs:заказывать{}, // заказывать на сайте rus_verbs:осуществить{}, // осуществить на практике rus_verbs:обосноваться{}, // обосноваться на верхушке rus_verbs:пытать{}, // пытать на электрическом стуле rus_verbs:совершиться{}, // совершиться на заседании rus_verbs:свернуться{}, // свернуться на медленном огне rus_verbs:пролетать{}, // пролетать на дельтаплане rus_verbs:сбыться{}, // сбыться на самом деле rus_verbs:разговориться{}, // разговориться на уроке rus_verbs:разворачиваться{}, // разворачиваться на перекрестке rus_verbs:преподнести{}, // преподнести на блюдечке rus_verbs:напечатать{}, // напечатать на лазернике rus_verbs:прорвать{}, // прорвать на периферии rus_verbs:раскачиваться{}, // раскачиваться на доске rus_verbs:задерживаться{}, // задерживаться на старте rus_verbs:угощать{}, // угощать на вечеринке rus_verbs:шарить{}, // шарить на столе rus_verbs:увеличивать{}, // увеличивать на первом этапе rus_verbs:рехнуться{}, // рехнуться на старости лет rus_verbs:расцвести{}, // расцвести на грядке rus_verbs:закипеть{}, // закипеть на плите rus_verbs:подлететь{}, // подлететь на параплане rus_verbs:рыться{}, // рыться на свалке rus_verbs:добираться{}, // добираться на попутках rus_verbs:продержаться{}, // продержаться на вершине rus_verbs:разыскивать{}, // разыскивать на выставках rus_verbs:освобождать{}, // освобождать на заседании rus_verbs:передвигаться{}, // передвигаться на самокате rus_verbs:проявиться{}, // проявиться на свету rus_verbs:заскользить{}, // заскользить на льду rus_verbs:пересказать{}, // пересказать на сцене студенческого театра rus_verbs:протестовать{}, // протестовать на улице rus_verbs:указываться{}, // указываться на табличках rus_verbs:прискакать{}, // прискакать на лошадке rus_verbs:копошиться{}, // копошиться на свежем воздухе rus_verbs:подсчитать{}, // подсчитать на бумажке rus_verbs:разволноваться{}, // разволноваться на экзамене rus_verbs:завертеться{}, // завертеться на полу rus_verbs:ознакомиться{}, // ознакомиться на ходу rus_verbs:ржать{}, // ржать на уроке rus_verbs:раскинуть{}, // раскинуть на грядках rus_verbs:разгромить{}, // разгромить на ринге rus_verbs:подслушать{}, // подслушать на совещании rus_verbs:описываться{}, // описываться на страницах книги rus_verbs:качаться{}, // качаться на стуле rus_verbs:усилить{}, // усилить на флангах rus_verbs:набросать{}, // набросать на клочке картона rus_verbs:расстреливать{}, // расстреливать на подходе rus_verbs:запрыгать{}, // запрыгать на одной ноге rus_verbs:сыскать{}, // сыскать на чужбине rus_verbs:подтвердиться{}, // подтвердиться на практике rus_verbs:плескаться{}, // плескаться на мелководье rus_verbs:расширяться{}, // расширяться на конце rus_verbs:подержать{}, // подержать на солнце rus_verbs:планироваться{}, // планироваться на общем собрании rus_verbs:сгинуть{}, // сгинуть на чужбине rus_verbs:замкнуться{}, // замкнуться на точке rus_verbs:закачаться{}, // закачаться на ветру rus_verbs:перечитывать{}, // перечитывать на ходу rus_verbs:перелететь{}, // перелететь на дельтаплане rus_verbs:оживать{}, // оживать на солнце rus_verbs:женить{}, // женить на богатой невесте rus_verbs:заглохнуть{}, // заглохнуть на старте rus_verbs:копаться{}, // копаться на полу rus_verbs:развлекаться{}, // развлекаться на дискотеке rus_verbs:печататься{}, // печататься на струйном принтере rus_verbs:обрываться{}, // обрываться на полуслове rus_verbs:ускакать{}, // ускакать на лошадке rus_verbs:подписывать{}, // подписывать на столе rus_verbs:добывать{}, // добывать на выработке rus_verbs:скопиться{}, // скопиться на выходе rus_verbs:повстречать{}, // повстречать на пути rus_verbs:поцеловаться{}, // поцеловаться на площади rus_verbs:растянуть{}, // растянуть на столе rus_verbs:подаваться{}, // подаваться на благотворительном обеде rus_verbs:повстречаться{}, // повстречаться на митинге rus_verbs:примоститься{}, // примоститься на ступеньках rus_verbs:отразить{}, // отразить на страницах доклада rus_verbs:пояснять{}, // пояснять на страницах приложения rus_verbs:накормить{}, // накормить на кухне rus_verbs:поужинать{}, // поужинать на веранде инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге деепричастие:спев{}, инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить на мелководье rus_verbs:освоить{}, // освоить на практике rus_verbs:распластаться{}, // распластаться на травке rus_verbs:отплыть{}, // отплыть на старом каяке rus_verbs:улетать{}, // улетать на любом самолете rus_verbs:отстаивать{}, // отстаивать на корте rus_verbs:осуждать{}, // осуждать на словах rus_verbs:переговорить{}, // переговорить на обеде rus_verbs:укрыть{}, // укрыть на чердаке rus_verbs:томиться{}, // томиться на привязи rus_verbs:сжигать{}, // сжигать на полигоне rus_verbs:позавтракать{}, // позавтракать на лоне природы rus_verbs:функционировать{}, // функционирует на солнечной энергии rus_verbs:разместить{}, // разместить на сайте rus_verbs:пронести{}, // пронести на теле rus_verbs:нашарить{}, // нашарить на столе rus_verbs:корчиться{}, // корчиться на полу rus_verbs:распознать{}, // распознать на снимке rus_verbs:повеситься{}, // повеситься на шнуре rus_verbs:обозначиться{}, // обозначиться на картах rus_verbs:оступиться{}, // оступиться на скользком льду rus_verbs:подносить{}, // подносить на блюдечке rus_verbs:расстелить{}, // расстелить на газоне rus_verbs:обсуждаться{}, // обсуждаться на собрании rus_verbs:расписаться{}, // расписаться на бланке rus_verbs:плестись{}, // плестись на привязи rus_verbs:объявиться{}, // объявиться на сцене rus_verbs:повышаться{}, // повышаться на первом датчике rus_verbs:разрабатывать{}, // разрабатывать на заводе rus_verbs:прерывать{}, // прерывать на середине rus_verbs:каяться{}, // каяться на публике rus_verbs:освоиться{}, // освоиться на лошади rus_verbs:подплыть{}, // подплыть на плоту rus_verbs:оскорбить{}, // оскорбить на митинге rus_verbs:торжествовать{}, // торжествовать на пьедестале rus_verbs:поправлять{}, // поправлять на одежде rus_verbs:отражать{}, // отражать на картине rus_verbs:дремать{}, // дремать на кушетке rus_verbs:применяться{}, // применяться на производстве стали rus_verbs:поражать{}, // поражать на большой дистанции rus_verbs:расстрелять{}, // расстрелять на окраине хутора rus_verbs:рассчитать{}, // рассчитать на калькуляторе rus_verbs:записывать{}, // записывать на ленте rus_verbs:перебирать{}, // перебирать на ладони rus_verbs:разбиться{}, // разбиться на катере rus_verbs:поискать{}, // поискать на ферме rus_verbs:прятать{}, // прятать на заброшенном складе rus_verbs:пропеть{}, // пропеть на эстраде rus_verbs:замелькать{}, // замелькать на экране rus_verbs:грустить{}, // грустить на веранде rus_verbs:крутить{}, // крутить на оси rus_verbs:подготовить{}, // подготовить на конспиративной квартире rus_verbs:различать{}, // различать на картинке rus_verbs:киснуть{}, // киснуть на чужбине rus_verbs:оборваться{}, // оборваться на полуслове rus_verbs:запутаться{}, // запутаться на простейшем тесте rus_verbs:общаться{}, // общаться на уроке rus_verbs:производиться{}, // производиться на фабрике rus_verbs:сочинить{}, // сочинить на досуге rus_verbs:давить{}, // давить на лице rus_verbs:разработать{}, // разработать на секретном предприятии rus_verbs:качать{}, // качать на качелях rus_verbs:тушить{}, // тушить на крыше пожар rus_verbs:охранять{}, // охранять на территории базы rus_verbs:приметить{}, // приметить на взгорке rus_verbs:скрыть{}, // скрыть на теле rus_verbs:удерживать{}, // удерживать на руке rus_verbs:усвоить{}, // усвоить на уроке rus_verbs:растаять{}, // растаять на солнечной стороне rus_verbs:красоваться{}, // красоваться на виду rus_verbs:сохраняться{}, // сохраняться на холоде rus_verbs:лечить{}, // лечить на дому rus_verbs:прокатиться{}, // прокатиться на уницикле rus_verbs:договариваться{}, // договариваться на нейтральной территории rus_verbs:качнуться{}, // качнуться на одной ноге rus_verbs:опубликовать{}, // опубликовать на сайте rus_verbs:отражаться{}, // отражаться на поверхности воды rus_verbs:обедать{}, // обедать на веранде rus_verbs:посидеть{}, // посидеть на лавочке rus_verbs:сообщаться{}, // сообщаться на официальном сайте rus_verbs:свершиться{}, // свершиться на заседании rus_verbs:ночевать{}, // ночевать на даче rus_verbs:темнеть{}, // темнеть на свету rus_verbs:гибнуть{}, // гибнуть на территории полигона rus_verbs:усиливаться{}, // усиливаться на территории округа rus_verbs:проживать{}, // проживать на даче rus_verbs:исследовать{}, // исследовать на большой глубине rus_verbs:обитать{}, // обитать на громадной глубине rus_verbs:сталкиваться{}, // сталкиваться на большой высоте rus_verbs:таиться{}, // таиться на большой глубине rus_verbs:спасать{}, // спасать на пожаре rus_verbs:сказываться{}, // сказываться на общем результате rus_verbs:заблудиться{}, // заблудиться на стройке rus_verbs:пошарить{}, // пошарить на полках rus_verbs:планировать{}, // планировать на бумаге rus_verbs:ранить{}, // ранить на полигоне rus_verbs:хлопать{}, // хлопать на сцене rus_verbs:основать{}, // основать на горе новый монастырь rus_verbs:отбить{}, // отбить на столе rus_verbs:отрицать{}, // отрицать на заседании комиссии rus_verbs:устоять{}, // устоять на ногах rus_verbs:отзываться{}, // отзываться на страницах отчёта rus_verbs:притормозить{}, // притормозить на обочине rus_verbs:читаться{}, // читаться на лице rus_verbs:заиграть{}, // заиграть на саксофоне rus_verbs:зависнуть{}, // зависнуть на игровой площадке rus_verbs:сознаться{}, // сознаться на допросе rus_verbs:выясняться{}, // выясняться на очной ставке rus_verbs:наводить{}, // наводить на столе порядок rus_verbs:покоиться{}, // покоиться на кладбище rus_verbs:значиться{}, // значиться на бейджике rus_verbs:съехать{}, // съехать на санках rus_verbs:познакомить{}, // познакомить на свадьбе rus_verbs:завязать{}, // завязать на спине rus_verbs:грохнуть{}, // грохнуть на площади rus_verbs:разъехаться{}, // разъехаться на узкой дороге rus_verbs:столпиться{}, // столпиться на крыльце rus_verbs:порыться{}, // порыться на полках rus_verbs:ослабить{}, // ослабить на шее rus_verbs:оправдывать{}, // оправдывать на суде rus_verbs:обнаруживаться{}, // обнаруживаться на складе rus_verbs:спастись{}, // спастись на дереве rus_verbs:прерваться{}, // прерваться на полуслове rus_verbs:строиться{}, // строиться на пустыре rus_verbs:познать{}, // познать на практике rus_verbs:путешествовать{}, // путешествовать на поезде rus_verbs:побеждать{}, // побеждать на ринге rus_verbs:рассматриваться{}, // рассматриваться на заседании rus_verbs:продаваться{}, // продаваться на открытом рынке rus_verbs:разместиться{}, // разместиться на базе rus_verbs:завыть{}, // завыть на холме rus_verbs:настигнуть{}, // настигнуть на окраине rus_verbs:укрыться{}, // укрыться на чердаке rus_verbs:расплакаться{}, // расплакаться на заседании комиссии rus_verbs:заканчивать{}, // заканчивать на последнем задании rus_verbs:пролежать{}, // пролежать на столе rus_verbs:громоздиться{}, // громоздиться на полу rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе rus_verbs:поскользнуться{}, // поскользнуться на льду rus_verbs:таскать{}, // таскать на спине rus_verbs:просматривать{}, // просматривать на сайте rus_verbs:обдумать{}, // обдумать на досуге rus_verbs:гадать{}, // гадать на кофейной гуще rus_verbs:останавливать{}, // останавливать на выходе rus_verbs:обозначать{}, // обозначать на странице rus_verbs:долететь{}, // долететь на спортивном байке rus_verbs:тесниться{}, // тесниться на чердачке rus_verbs:хоронить{}, // хоронить на частном кладбище rus_verbs:установиться{}, // установиться на юге rus_verbs:прикидывать{}, // прикидывать на клочке бумаги rus_verbs:затаиться{}, // затаиться на дереве rus_verbs:раздобыть{}, // раздобыть на складе rus_verbs:перебросить{}, // перебросить на вертолетах rus_verbs:захватывать{}, // захватывать на базе rus_verbs:сказаться{}, // сказаться на итоговых оценках rus_verbs:покачиваться{}, // покачиваться на волнах rus_verbs:крутиться{}, // крутиться на кухне rus_verbs:помещаться{}, // помещаться на полке rus_verbs:питаться{}, // питаться на помойке rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле rus_verbs:кататься{}, // кататься на велике rus_verbs:поработать{}, // поработать на стройке rus_verbs:ограбить{}, // ограбить на пустыре rus_verbs:зарабатывать{}, // зарабатывать на бирже rus_verbs:преуспеть{}, // преуспеть на ниве искусства rus_verbs:заерзать{}, // заерзать на стуле rus_verbs:разъяснить{}, // разъяснить на полях rus_verbs:отчеканить{}, // отчеканить на медной пластине rus_verbs:торговать{}, // торговать на рынке rus_verbs:поколебаться{}, // поколебаться на пороге rus_verbs:прикинуть{}, // прикинуть на бумажке rus_verbs:рассечь{}, // рассечь на тупом конце rus_verbs:посмеяться{}, // посмеяться на переменке rus_verbs:остыть{}, // остыть на морозном воздухе rus_verbs:запереться{}, // запереться на чердаке rus_verbs:обогнать{}, // обогнать на повороте rus_verbs:подтянуться{}, // подтянуться на турнике rus_verbs:привозить{}, // привозить на машине rus_verbs:подбирать{}, // подбирать на полу rus_verbs:уничтожать{}, // уничтожать на подходе rus_verbs:притаиться{}, // притаиться на вершине rus_verbs:плясать{}, // плясать на костях rus_verbs:поджидать{}, // поджидать на вокзале rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!) rus_verbs:смениться{}, // смениться на посту rus_verbs:посчитать{}, // посчитать на пальцах rus_verbs:прицелиться{}, // прицелиться на бегу rus_verbs:нарисовать{}, // нарисовать на стене rus_verbs:прыгать{}, // прыгать на сцене rus_verbs:повертеть{}, // повертеть на пальце rus_verbs:попрощаться{}, // попрощаться на панихиде инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване rus_verbs:разобрать{}, // разобрать на столе rus_verbs:помереть{}, // помереть на чужбине rus_verbs:различить{}, // различить на нечеткой фотографии rus_verbs:рисовать{}, // рисовать на доске rus_verbs:проследить{}, // проследить на экране rus_verbs:задремать{}, // задремать на диване rus_verbs:ругаться{}, // ругаться на людях rus_verbs:сгореть{}, // сгореть на работе rus_verbs:зазвучать{}, // зазвучать на коротких волнах rus_verbs:задохнуться{}, // задохнуться на вершине горы rus_verbs:порождать{}, // порождать на поверхности небольшую рябь rus_verbs:отдыхать{}, // отдыхать на курорте rus_verbs:образовать{}, // образовать на дне толстый слой rus_verbs:поправиться{}, // поправиться на дармовых харчах rus_verbs:отмечать{}, // отмечать на календаре rus_verbs:реять{}, // реять на флагштоке rus_verbs:ползти{}, // ползти на коленях rus_verbs:продавать{}, // продавать на аукционе rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче rus_verbs:рыскать{}, // мышки рыскали на кухне rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы rus_verbs:напасть{}, // напасть на территории другого государства rus_verbs:издать{}, // издать на западе rus_verbs:оставаться{}, // оставаться на страже порядка rus_verbs:появиться{}, // наконец появиться на экране rus_verbs:лежать{}, // лежать на столе rus_verbs:ждать{}, // ждать на берегу инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге глагол:писать{aux stress="пис^ать"}, rus_verbs:оказываться{}, // оказываться на полу rus_verbs:поставить{}, // поставить на столе rus_verbs:держать{}, // держать на крючке rus_verbs:выходить{}, // выходить на остановке rus_verbs:заговорить{}, // заговорить на китайском языке rus_verbs:ожидать{}, // ожидать на стоянке rus_verbs:закричать{}, // закричал на минарете муэдзин rus_verbs:простоять{}, // простоять на посту rus_verbs:продолжить{}, // продолжить на первом этаже rus_verbs:ощутить{}, // ощутить на себе влияние кризиса rus_verbs:состоять{}, // состоять на учете rus_verbs:готовиться{}, инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте глагол:акклиматизироваться{вид:несоверш}, rus_verbs:арестовать{}, // грабители были арестованы на месте преступления rus_verbs:схватить{}, // грабители были схвачены на месте преступления инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе глагол:атаковать{ вид:соверш }, прилагательное:атакованный{ вид:соверш }, прилагательное:атаковавший{ вид:соверш }, rus_verbs:базировать{}, // установка будет базирована на границе rus_verbs:базироваться{}, // установка базируется на границе rus_verbs:барахтаться{}, // дети барахтались на мелководье rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке rus_verbs:бренчать{}, // парень что-то бренчал на гитаре rus_verbs:бренькать{}, // парень что-то бренькает на гитаре rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории. rus_verbs:буксовать{}, // Колеса буксуют на льду rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле rus_verbs:взвести{}, // Боец взвел на оружии предохранитель rus_verbs:вилять{}, // Машина сильно виляла на дороге rus_verbs:висеть{}, // Яблоко висит на ветке rus_verbs:возлежать{}, // возлежать на лежанке rus_verbs:подниматься{}, // Мы поднимаемся на лифте rus_verbs:подняться{}, // Мы поднимемся на лифте rus_verbs:восседать{}, // Коля восседает на лошади rus_verbs:воссиять{}, // Луна воссияла на небе rus_verbs:воцариться{}, // Мир воцарился на всей земле rus_verbs:воцаряться{}, // Мир воцаряется на всей земле rus_verbs:вращать{}, // вращать на поясе rus_verbs:вращаться{}, // вращаться на поясе rus_verbs:встретить{}, // встретить друга на улице rus_verbs:встретиться{}, // встретиться на занятиях rus_verbs:встречать{}, // встречать на занятиях rus_verbs:въебывать{}, // въебывать на работе rus_verbs:въезжать{}, // въезжать на автомобиле rus_verbs:въехать{}, // въехать на автомобиле rus_verbs:выгорать{}, // ткань выгорает на солнце rus_verbs:выгореть{}, // ткань выгорела на солнце rus_verbs:выгравировать{}, // выгравировать на табличке надпись rus_verbs:выжить{}, // выжить на необитаемом острове rus_verbs:вылежаться{}, // помидоры вылежались на солнце rus_verbs:вылеживаться{}, // вылеживаться на солнце rus_verbs:выместить{}, // выместить на ком-то злобу rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение rus_verbs:вымещаться{}, // вымещаться на ком-то rus_verbs:выращивать{}, // выращивать на грядке помидоры rus_verbs:выращиваться{}, // выращиваться на грядке инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись глагол:вырезать{вид:соверш}, инфинитив:вырезать{вид:несоверш}, глагол:вырезать{вид:несоверш}, rus_verbs:вырисоваться{}, // вырисоваться на графике rus_verbs:вырисовываться{}, // вырисовываться на графике rus_verbs:высаживать{}, // высаживать на необитаемом острове rus_verbs:высаживаться{}, // высаживаться на острове rus_verbs:высвечивать{}, // высвечивать на дисплее температуру rus_verbs:высвечиваться{}, // высвечиваться на дисплее rus_verbs:выстроить{}, // выстроить на фундаменте rus_verbs:выстроиться{}, // выстроиться на плацу rus_verbs:выстудить{}, // выстудить на морозе rus_verbs:выстудиться{}, // выстудиться на морозе rus_verbs:выстужать{}, // выстужать на морозе rus_verbs:выстуживать{}, // выстуживать на морозе rus_verbs:выстуживаться{}, // выстуживаться на морозе rus_verbs:выстукать{}, // выстукать на клавиатуре rus_verbs:выстукивать{}, // выстукивать на клавиатуре rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре rus_verbs:выступать{}, // выступать на сцене rus_verbs:выступить{}, // выступить на сцене rus_verbs:выстучать{}, // выстучать на клавиатуре rus_verbs:выстывать{}, // выстывать на морозе rus_verbs:выстыть{}, // выстыть на морозе rus_verbs:вытатуировать{}, // вытатуировать на руке якорь rus_verbs:говорить{}, // говорить на повышенных тонах rus_verbs:заметить{}, // заметить на берегу rus_verbs:стоять{}, // твёрдо стоять на ногах rus_verbs:оказаться{}, // оказаться на передовой линии rus_verbs:почувствовать{}, // почувствовать на своей шкуре rus_verbs:остановиться{}, // остановиться на первом пункте rus_verbs:показаться{}, // показаться на горизонте rus_verbs:чувствовать{}, // чувствовать на своей шкуре rus_verbs:искать{}, // искать на открытом пространстве rus_verbs:иметься{}, // иметься на складе rus_verbs:клясться{}, // клясться на Коране rus_verbs:прервать{}, // прервать на полуслове rus_verbs:играть{}, // играть на чувствах rus_verbs:спуститься{}, // спуститься на парашюте rus_verbs:понадобиться{}, // понадобиться на экзамене rus_verbs:служить{}, // служить на флоте rus_verbs:подобрать{}, // подобрать на улице rus_verbs:появляться{}, // появляться на сцене rus_verbs:селить{}, // селить на чердаке rus_verbs:поймать{}, // поймать на границе rus_verbs:увидать{}, // увидать на опушке rus_verbs:подождать{}, // подождать на перроне rus_verbs:прочесть{}, // прочесть на полях rus_verbs:тонуть{}, // тонуть на мелководье rus_verbs:ощущать{}, // ощущать на коже rus_verbs:отметить{}, // отметить на полях rus_verbs:показывать{}, // показывать на графике rus_verbs:разговаривать{}, // разговаривать на иностранном языке rus_verbs:прочитать{}, // прочитать на сайте rus_verbs:попробовать{}, // попробовать на практике rus_verbs:замечать{}, // замечать на коже грязь rus_verbs:нести{}, // нести на плечах rus_verbs:носить{}, // носить на голове rus_verbs:гореть{}, // гореть на работе rus_verbs:застыть{}, // застыть на пороге инфинитив:жениться{ вид:соверш }, // жениться на королеве глагол:жениться{ вид:соверш }, прилагательное:женатый{}, прилагательное:женившийся{}, rus_verbs:спрятать{}, // спрятать на чердаке rus_verbs:развернуться{}, // развернуться на плацу rus_verbs:строить{}, // строить на песке rus_verbs:устроить{}, // устроить на даче тестральный вечер rus_verbs:настаивать{}, // настаивать на выполнении приказа rus_verbs:находить{}, // находить на берегу rus_verbs:мелькнуть{}, // мелькнуть на экране rus_verbs:очутиться{}, // очутиться на опушке леса инфинитив:использовать{вид:соверш}, // использовать на работе глагол:использовать{вид:соверш}, инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, прилагательное:использованный{}, прилагательное:использующий{}, прилагательное:использовавший{}, rus_verbs:лететь{}, // лететь на воздушном шаре rus_verbs:смеяться{}, // смеяться на сцене rus_verbs:ездить{}, // ездить на мопеде rus_verbs:заснуть{}, // заснуть на диване rus_verbs:застать{}, // застать на рабочем месте rus_verbs:очнуться{}, // очнуться на больничной койке rus_verbs:разглядеть{}, // разглядеть на фотографии rus_verbs:обойти{}, // обойти на вираже rus_verbs:удержаться{}, // удержаться на троне rus_verbs:побывать{}, // побывать на другой планете rus_verbs:заняться{}, // заняться на выходных делом rus_verbs:вянуть{}, // вянуть на солнце rus_verbs:постоять{}, // постоять на голове rus_verbs:приобрести{}, // приобрести на распродаже rus_verbs:попасться{}, // попасться на краже rus_verbs:продолжаться{}, // продолжаться на земле rus_verbs:открывать{}, // открывать на арене rus_verbs:создавать{}, // создавать на сцене rus_verbs:обсуждать{}, // обсуждать на кухне rus_verbs:отыскать{}, // отыскать на полу rus_verbs:уснуть{}, // уснуть на диване rus_verbs:задержаться{}, // задержаться на работе rus_verbs:курить{}, // курить на свежем воздухе rus_verbs:приподняться{}, // приподняться на локтях rus_verbs:установить{}, // установить на вершине rus_verbs:запереть{}, // запереть на балконе rus_verbs:синеть{}, // синеть на воздухе rus_verbs:убивать{}, // убивать на нейтральной территории rus_verbs:скрываться{}, // скрываться на даче rus_verbs:родить{}, // родить на полу rus_verbs:описать{}, // описать на страницах книги rus_verbs:перехватить{}, // перехватить на подлете rus_verbs:скрывать{}, // скрывать на даче rus_verbs:сменить{}, // сменить на посту rus_verbs:мелькать{}, // мелькать на экране rus_verbs:присутствовать{}, // присутствовать на мероприятии rus_verbs:украсть{}, // украсть на рынке rus_verbs:победить{}, // победить на ринге rus_verbs:упомянуть{}, // упомянуть на страницах романа rus_verbs:плыть{}, // плыть на старой лодке rus_verbs:повиснуть{}, // повиснуть на перекладине rus_verbs:нащупать{}, // нащупать на дне rus_verbs:затихнуть{}, // затихнуть на дне rus_verbs:построить{}, // построить на участке rus_verbs:поддерживать{}, // поддерживать на поверхности rus_verbs:заработать{}, // заработать на бирже rus_verbs:провалиться{}, // провалиться на экзамене rus_verbs:сохранить{}, // сохранить на диске rus_verbs:располагаться{}, // располагаться на софе rus_verbs:поклясться{}, // поклясться на библии rus_verbs:сражаться{}, // сражаться на арене rus_verbs:спускаться{}, // спускаться на дельтаплане rus_verbs:уничтожить{}, // уничтожить на подступах rus_verbs:изучить{}, // изучить на практике rus_verbs:рождаться{}, // рождаться на праздниках rus_verbs:прилететь{}, // прилететь на самолете rus_verbs:догнать{}, // догнать на перекрестке rus_verbs:изобразить{}, // изобразить на бумаге rus_verbs:проехать{}, // проехать на тракторе rus_verbs:приготовить{}, // приготовить на масле rus_verbs:споткнуться{}, // споткнуться на полу rus_verbs:собирать{}, // собирать на берегу rus_verbs:отсутствовать{}, // отсутствовать на тусовке rus_verbs:приземлиться{}, // приземлиться на военном аэродроме rus_verbs:сыграть{}, // сыграть на трубе rus_verbs:прятаться{}, // прятаться на даче rus_verbs:спрятаться{}, // спрятаться на чердаке rus_verbs:провозгласить{}, // провозгласить на митинге rus_verbs:изложить{}, // изложить на бумаге rus_verbs:использоваться{}, // использоваться на практике rus_verbs:замяться{}, // замяться на входе rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота rus_verbs:сверкнуть{}, // сверкнуть на солнце rus_verbs:сверкать{}, // сверкать на свету rus_verbs:задержать{}, // задержать на митинге rus_verbs:осечься{}, // осечься на первом слове rus_verbs:хранить{}, // хранить на банковском счету rus_verbs:шутить{}, // шутить на уроке rus_verbs:кружиться{}, // кружиться на балу rus_verbs:чертить{}, // чертить на доске rus_verbs:отразиться{}, // отразиться на оценках rus_verbs:греть{}, // греть на солнце rus_verbs:рассуждать{}, // рассуждать на страницах своей книги rus_verbs:окружать{}, // окружать на острове rus_verbs:сопровождать{}, // сопровождать на охоте rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте rus_verbs:содержаться{}, // содержаться на приусадебном участке rus_verbs:поселиться{}, // поселиться на даче rus_verbs:запеть{}, // запеть на сцене инфинитив:провозить{ вид:несоверш }, // провозить на теле глагол:провозить{ вид:несоверш }, прилагательное:провезенный{}, прилагательное:провозивший{вид:несоверш}, прилагательное:провозящий{вид:несоверш}, деепричастие:провозя{}, rus_verbs:мочить{}, // мочить на месте rus_verbs:преследовать{}, // преследовать на территории другого штата rus_verbs:пролететь{}, // пролетел на параплане rus_verbs:драться{}, // драться на рапирах rus_verbs:просидеть{}, // просидеть на занятиях rus_verbs:убираться{}, // убираться на балконе rus_verbs:таять{}, // таять на солнце rus_verbs:проверять{}, // проверять на полиграфе rus_verbs:убеждать{}, // убеждать на примере rus_verbs:скользить{}, // скользить на льду rus_verbs:приобретать{}, // приобретать на распродаже rus_verbs:летать{}, // летать на метле rus_verbs:толпиться{}, // толпиться на перроне rus_verbs:плавать{}, // плавать на надувном матрасе rus_verbs:описывать{}, // описывать на страницах повести rus_verbs:пробыть{}, // пробыть на солнце слишком долго rus_verbs:застрять{}, // застрять на верхнем этаже rus_verbs:метаться{}, // метаться на полу rus_verbs:сжечь{}, // сжечь на костре rus_verbs:расслабиться{}, // расслабиться на кушетке rus_verbs:услыхать{}, // услыхать на рынке rus_verbs:удержать{}, // удержать на прежнем уровне rus_verbs:образоваться{}, // образоваться на дне rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа rus_verbs:уезжать{}, // уезжать на попутке rus_verbs:похоронить{}, // похоронить на закрытом кладбище rus_verbs:настоять{}, // настоять на пересмотре оценок rus_verbs:растянуться{}, // растянуться на горячем песке rus_verbs:покрутить{}, // покрутить на шесте rus_verbs:обнаружиться{}, // обнаружиться на болоте rus_verbs:гулять{}, // гулять на свадьбе rus_verbs:утонуть{}, // утонуть на курорте rus_verbs:храниться{}, // храниться на депозите rus_verbs:танцевать{}, // танцевать на свадьбе rus_verbs:трудиться{}, // трудиться на заводе инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати глагол:засыпать{переходность:непереходный вид:несоверш}, деепричастие:засыпая{переходность:непереходный вид:несоверш}, прилагательное:засыпавший{переходность:непереходный вид:несоверш}, прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках rus_verbs:сушить{}, // сушить на открытом воздухе rus_verbs:зашевелиться{}, // зашевелиться на чердаке rus_verbs:обдумывать{}, // обдумывать на досуге rus_verbs:докладывать{}, // докладывать на научной конференции rus_verbs:промелькнуть{}, // промелькнуть на экране // прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории прилагательное:написанный{}, // слово, написанное на заборе rus_verbs:умещаться{}, // компьютер, умещающийся на ладони rus_verbs:открыть{}, // книга, открытая на последней странице rus_verbs:спать{}, // йог, спящий на гвоздях rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте rus_verbs:отобразиться{}, // удивление, отобразившееся на лице rus_verbs:увидеть{}, // на полу я увидел чьи-то следы rus_verbs:видеть{}, // на полу я вижу чьи-то следы rus_verbs:оставить{}, // Мел оставил на доске белый след. rus_verbs:оставлять{}, // Мел оставляет на доске белый след. rus_verbs:встречаться{}, // встречаться на лекциях rus_verbs:познакомиться{}, // познакомиться на занятиях rus_verbs:устроиться{}, // она устроилась на кровати rus_verbs:ложиться{}, // ложись на полу rus_verbs:останавливаться{}, // останавливаться на достигнутом rus_verbs:спотыкаться{}, // спотыкаться на ровном месте rus_verbs:распечатать{}, // распечатать на бумаге rus_verbs:распечатывать{}, // распечатывать на бумаге rus_verbs:просмотреть{}, // просмотреть на бумаге rus_verbs:закрепляться{}, // закрепляться на плацдарме rus_verbs:погреться{}, // погреться на солнышке rus_verbs:мешать{}, // Он мешал краски на палитре. rus_verbs:занять{}, // Он занял первое место на соревнованиях. rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках. деепричастие:женившись{ вид:соверш }, rus_verbs:везти{}, // Он везёт песок на тачке. прилагательное:казненный{}, // Он был казнён на электрическом стуле. rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче. rus_verbs:принести{}, // Официантка принесла нам обед на подносе. rus_verbs:переписать{}, // Перепишите эту рукопись на машинке. rus_verbs:идти{}, // Поезд идёт на малой скорости. rus_verbs:петь{}, // птички поют на рассвете rus_verbs:смотреть{}, // Смотри на обороте. rus_verbs:прибрать{}, // прибрать на столе rus_verbs:прибраться{}, // прибраться на столе rus_verbs:растить{}, // растить капусту на огороде rus_verbs:тащить{}, // тащить ребенка на руках rus_verbs:убирать{}, // убирать на столе rus_verbs:простыть{}, // Я простыл на морозе. rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе. rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках. rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге. rus_verbs:вскочить{}, // У него вскочил прыщ на носу. rus_verbs:свить{}, // У нас на балконе воробей свил гнездо. rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица. rus_verbs:восходить{}, // Солнце восходит на востоке. rus_verbs:блестеть{}, // Снег блестит на солнце. rus_verbs:побить{}, // Рысак побил всех лошадей на скачках. rus_verbs:литься{}, // Реки крови льются на войне. rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах. rus_verbs:клубиться{}, // Пыль клубится на дороге. инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке. // глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути // инфинитив:находиться{вид:несоверш}, rus_verbs:жить{}, // Было интересно жить на курорте. rus_verbs:повидать{}, // Он много повидал на своём веку. rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду. rus_verbs:расположиться{}, // Оба села расположились на берегу реки. rus_verbs:объясняться{}, // Они объясняются на иностранном языке. rus_verbs:прощаться{}, // Они долго прощались на вокзале. rus_verbs:работать{}, // Она работает на ткацкой фабрике. rus_verbs:купить{}, // Она купила молоко на рынке. rus_verbs:поместиться{}, // Все книги поместились на полке. глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике. rus_verbs:пожить{}, // Недолго она пожила на свете. rus_verbs:краснеть{}, // Небо краснеет на закате. rus_verbs:бывать{}, // На Волге бывает сильное волнение. rus_verbs:ехать{}, // Мы туда ехали на автобусе. rus_verbs:провести{}, // Мы провели месяц на даче. rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице. rus_verbs:расти{}, // Арбузы растут теперь не только на юге. ГЛ_ИНФ(сидеть), // три больших пса сидят на траве ГЛ_ИНФ(сесть), // три больших пса сели на траву ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль ГЛ_ИНФ(повезти), // я повезу тебя на машине ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси ГЛ_ИНФ(пить), // пить на кухне чай ГЛ_ИНФ(найти), // найти на острове ГЛ_ИНФ(быть), // на этих костях есть следы зубов ГЛ_ИНФ(высадиться), // помощники высадились на острове ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове ГЛ_ИНФ(случиться), // это случилось на опушке леса ГЛ_ИНФ(продать), ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: смотреть на youtube fact гл_предл { if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} } then return true } // локатив fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} } then return true } #endregion ПРЕДЛОЖНЫЙ #region ВИНИТЕЛЬНЫЙ // НА+винительный падеж: // ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ #region VerbList wordentry_set Гл_НА_Вин= { rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили. rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку. rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай. rus_verbs:умножить{}, // Умножьте это количество примерно на 10. //rus_verbs:умножать{}, rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу. rus_verbs:откатывать{}, rus_verbs:доносить{}, // Вот и побежали на вас доносить. rus_verbs:донести{}, rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали. безлич_глагол:хватит{}, // - На одну атаку хватит. rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты. rus_verbs:поскупиться{}, // Не поскупись на похвалы! rus_verbs:подыматься{}, rus_verbs:транспортироваться{}, rus_verbs:бахнуть{}, // Бахнуть стакан на пол rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ) rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ) rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ) rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ) rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ) rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ) rus_verbs:БРЫЗГАТЬ{}, rus_verbs:БРЫЗНУТЬ{}, rus_verbs:КАПНУТЬ{}, rus_verbs:КАПАТЬ{}, rus_verbs:ПОКАПАТЬ{}, rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ) rus_verbs:ОХОТИТЬСЯ{}, // rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ) rus_verbs:НАРВАТЬСЯ{}, // rus_verbs:НАТОЛКНУТЬСЯ{}, // rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ) прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ) rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ) rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ) rus_verbs:СТАЛКИВАТЬ{}, // rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ) rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ) rus_verbs:ПЕРЕБРОСИТЬ{}, // rus_verbs:НАБРАСЫВАТЬ{}, // rus_verbs:НАБРОСИТЬ{}, // rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ) rus_verbs:СВОРАЧИВАТЬ{}, // // rus_verbs:ПОВЕРНУТЬ{}, // rus_verbs:ПОВОРАЧИВАТЬ{}, // rus_verbs:наорать{}, rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ) rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ) rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:перегонять{}, rus_verbs:выгонять{}, rus_verbs:выгнать{}, rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ) rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ) rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ) rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ) rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций rus_verbs:назначаться{}, // назначаться на пост rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин) rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА) // rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА) rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА) rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин) rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА) rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА) rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин) rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА) rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА) прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА) rus_verbs:посыпаться{}, // на Нину посыпались снежинки инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод. глагол:нарезаться{ вид:несоверш }, rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу rus_verbs:показать{}, // Вадим показал на Колю rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА) rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на) rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА) rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА) rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на) rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА) rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА) rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на) rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на) rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на) rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на) rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на) rus_verbs:верить{}, // верить людям на слово (верить на слово) rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру. rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору. rus_verbs:пасть{}, // Жребий пал на меня. rus_verbs:ездить{}, // Вчера мы ездили на оперу. rus_verbs:влезть{}, // Мальчик влез на дерево. rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу. rus_verbs:разбиться{}, // окно разбилось на мелкие осколки rus_verbs:бежать{}, // я бегу на урок rus_verbs:сбегаться{}, // сбегаться на происшествие rus_verbs:присылать{}, // присылать на испытание rus_verbs:надавить{}, // надавить на педать rus_verbs:внести{}, // внести законопроект на рассмотрение rus_verbs:вносить{}, // вносить законопроект на рассмотрение rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек. rus_verbs:оглядываться{}, // оглядываться на девушек rus_verbs:расходиться{}, // расходиться на отдых rus_verbs:поскакать{}, // поскакать на службу rus_verbs:прыгать{}, // прыгать на сцену rus_verbs:приглашать{}, // приглашать на обед rus_verbs:рваться{}, // Кусок ткани рвется на части rus_verbs:понестись{}, // понестись на волю rus_verbs:распространяться{}, // распространяться на всех жителей штата инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, деепричастие:просыпавшись{}, деепричастие:просыпаясь{}, rus_verbs:заехать{}, // заехать на пандус rus_verbs:разобрать{}, // разобрать на составляющие rus_verbs:опускаться{}, // опускаться на колени rus_verbs:переехать{}, // переехать на конспиративную квартиру rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов rus_verbs:поместить{}, // поместить на поднос rus_verbs:отходить{}, // отходить на подготовленные позиции rus_verbs:сыпаться{}, // сыпаться на плечи rus_verbs:отвезти{}, // отвезти на занятия rus_verbs:накинуть{}, // накинуть на плечи rus_verbs:отлететь{}, // отлететь на пол rus_verbs:закинуть{}, // закинуть на чердак rus_verbs:зашипеть{}, // зашипеть на собаку rus_verbs:прогреметь{}, // прогреметь на всю страну rus_verbs:повалить{}, // повалить на стол rus_verbs:опереть{}, // опереть на фундамент rus_verbs:забросить{}, // забросить на антресоль rus_verbs:подействовать{}, // подействовать на материал rus_verbs:разделять{}, // разделять на части rus_verbs:прикрикнуть{}, // прикрикнуть на детей rus_verbs:разложить{}, // разложить на множители rus_verbs:провожать{}, // провожать на работу rus_verbs:катить{}, // катить на стройку rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью rus_verbs:сохранять{}, // сохранять на память rus_verbs:злиться{}, // злиться на друга rus_verbs:оборачиваться{}, // оборачиваться на свист rus_verbs:сползти{}, // сползти на землю rus_verbs:записывать{}, // записывать на ленту rus_verbs:загнать{}, // загнать на дерево rus_verbs:забормотать{}, // забормотать на ухо rus_verbs:протиснуться{}, // протиснуться на самый край rus_verbs:заторопиться{}, // заторопиться на вручение премии rus_verbs:гаркнуть{}, // гаркнуть на шалунов rus_verbs:навалиться{}, // навалиться на виновника всей толпой rus_verbs:проскользнуть{}, // проскользнуть на крышу дома rus_verbs:подтянуть{}, // подтянуть на палубу rus_verbs:скатиться{}, // скатиться на двойки rus_verbs:давить{}, // давить на жалость rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства rus_verbs:замахнуться{}, // замахнуться на святое rus_verbs:заменить{}, // заменить на свежую салфетку rus_verbs:свалить{}, // свалить на землю rus_verbs:стекать{}, // стекать на оголенные провода rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов rus_verbs:развалиться{}, // развалиться на части rus_verbs:сердиться{}, // сердиться на товарища rus_verbs:обронить{}, // обронить на пол rus_verbs:подсесть{}, // подсесть на наркоту rus_verbs:реагировать{}, // реагировать на импульсы rus_verbs:отпускать{}, // отпускать на волю rus_verbs:прогнать{}, // прогнать на рабочее место rus_verbs:ложить{}, // ложить на стол rus_verbs:рвать{}, // рвать на части rus_verbs:разлететься{}, // разлететься на кусочки rus_verbs:превышать{}, // превышать на существенную величину rus_verbs:сбиться{}, // сбиться на рысь rus_verbs:пристроиться{}, // пристроиться на хорошую работу rus_verbs:удрать{}, // удрать на пастбище rus_verbs:толкать{}, // толкать на преступление rus_verbs:посматривать{}, // посматривать на экран rus_verbs:набирать{}, // набирать на судно rus_verbs:отступать{}, // отступать на дерево rus_verbs:подуть{}, // подуть на молоко rus_verbs:плеснуть{}, // плеснуть на голову rus_verbs:соскользнуть{}, // соскользнуть на землю rus_verbs:затаить{}, // затаить на кого-то обиду rus_verbs:обижаться{}, // обижаться на Колю rus_verbs:смахнуть{}, // смахнуть на пол rus_verbs:застегнуть{}, // застегнуть на все пуговицы rus_verbs:спускать{}, // спускать на землю rus_verbs:греметь{}, // греметь на всю округу rus_verbs:скосить{}, // скосить на соседа глаз rus_verbs:отважиться{}, // отважиться на прыжок rus_verbs:литься{}, // литься на землю rus_verbs:порвать{}, // порвать на тряпки rus_verbs:проследовать{}, // проследовать на сцену rus_verbs:надевать{}, // надевать на голову rus_verbs:проскочить{}, // проскочить на красный свет rus_verbs:прилечь{}, // прилечь на диванчик rus_verbs:разделиться{}, // разделиться на небольшие группы rus_verbs:завыть{}, // завыть на луну rus_verbs:переносить{}, // переносить на другую машину rus_verbs:наговорить{}, // наговорить на сотню рублей rus_verbs:намекать{}, // намекать на новые обстоятельства rus_verbs:нападать{}, // нападать на охранников rus_verbs:убегать{}, // убегать на другое место rus_verbs:тратить{}, // тратить на развлечения rus_verbs:присаживаться{}, // присаживаться на корточки rus_verbs:переместиться{}, // переместиться на вторую линию rus_verbs:завалиться{}, // завалиться на диван rus_verbs:удалиться{}, // удалиться на покой rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов rus_verbs:обрушить{}, // обрушить на голову rus_verbs:резать{}, // резать на части rus_verbs:умчаться{}, // умчаться на юг rus_verbs:навернуться{}, // навернуться на камень rus_verbs:примчаться{}, // примчаться на матч rus_verbs:издавать{}, // издавать на собственные средства rus_verbs:переключить{}, // переключить на другой язык rus_verbs:отправлять{}, // отправлять на пенсию rus_verbs:залечь{}, // залечь на дно rus_verbs:установиться{}, // установиться на диск rus_verbs:направлять{}, // направлять на дополнительное обследование rus_verbs:разрезать{}, // разрезать на части rus_verbs:оскалиться{}, // оскалиться на прохожего rus_verbs:рычать{}, // рычать на пьяных rus_verbs:погружаться{}, // погружаться на дно rus_verbs:опираться{}, // опираться на костыли rus_verbs:поторопиться{}, // поторопиться на учебу rus_verbs:сдвинуться{}, // сдвинуться на сантиметр rus_verbs:увеличить{}, // увеличить на процент rus_verbs:опускать{}, // опускать на землю rus_verbs:созвать{}, // созвать на митинг rus_verbs:делить{}, // делить на части rus_verbs:пробиться{}, // пробиться на заключительную часть rus_verbs:простираться{}, // простираться на много миль rus_verbs:забить{}, // забить на учебу rus_verbs:переложить{}, // переложить на чужие плечи rus_verbs:грохнуться{}, // грохнуться на землю rus_verbs:прорваться{}, // прорваться на сцену rus_verbs:разлить{}, // разлить на землю rus_verbs:укладываться{}, // укладываться на ночевку rus_verbs:уволить{}, // уволить на пенсию rus_verbs:наносить{}, // наносить на кожу rus_verbs:набежать{}, // набежать на берег rus_verbs:заявиться{}, // заявиться на стрельбище rus_verbs:налиться{}, // налиться на крышку rus_verbs:надвигаться{}, // надвигаться на берег rus_verbs:распустить{}, // распустить на каникулы rus_verbs:переключиться{}, // переключиться на другую задачу rus_verbs:чихнуть{}, // чихнуть на окружающих rus_verbs:шлепнуться{}, // шлепнуться на спину rus_verbs:устанавливать{}, // устанавливать на крышу rus_verbs:устанавливаться{}, // устанавливаться на крышу rus_verbs:устраиваться{}, // устраиваться на работу rus_verbs:пропускать{}, // пропускать на стадион инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, деепричастие:сбегав{}, деепричастие:сбегая{}, rus_verbs:показываться{}, // показываться на глаза rus_verbs:прибегать{}, // прибегать на урок rus_verbs:съездить{}, // съездить на ферму rus_verbs:прославиться{}, // прославиться на всю страну rus_verbs:опрокинуться{}, // опрокинуться на спину rus_verbs:насыпать{}, // насыпать на землю rus_verbs:употреблять{}, // употреблять на корм скоту rus_verbs:пристроить{}, // пристроить на работу rus_verbs:заворчать{}, // заворчать на вошедшего rus_verbs:завязаться{}, // завязаться на поставщиков rus_verbs:сажать{}, // сажать на стул rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры rus_verbs:заменять{}, // заменять на исправную rus_verbs:нацепить{}, // нацепить на голову rus_verbs:сыпать{}, // сыпать на землю rus_verbs:закрываться{}, // закрываться на ремонт rus_verbs:распространиться{}, // распространиться на всю популяцию rus_verbs:поменять{}, // поменять на велосипед rus_verbs:пересесть{}, // пересесть на велосипеды rus_verbs:подоспеть{}, // подоспеть на разбор rus_verbs:шипеть{}, // шипеть на собак rus_verbs:поделить{}, // поделить на части rus_verbs:подлететь{}, // подлететь на расстояние выстрела rus_verbs:нажимать{}, // нажимать на все кнопки rus_verbs:распасться{}, // распасться на части rus_verbs:приволочь{}, // приволочь на диван rus_verbs:пожить{}, // пожить на один доллар rus_verbs:устремляться{}, // устремляться на свободу rus_verbs:смахивать{}, // смахивать на пол rus_verbs:забежать{}, // забежать на обед rus_verbs:увеличиться{}, // увеличиться на существенную величину rus_verbs:прокрасться{}, // прокрасться на склад rus_verbs:пущать{}, // пущать на постой rus_verbs:отклонить{}, // отклонить на несколько градусов rus_verbs:насмотреться{}, // насмотреться на безобразия rus_verbs:настроить{}, // настроить на короткие волны rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров rus_verbs:поменяться{}, // поменяться на другую книжку rus_verbs:расколоться{}, // расколоться на части rus_verbs:разлиться{}, // разлиться на землю rus_verbs:срываться{}, // срываться на жену rus_verbs:осудить{}, // осудить на пожизненное заключение rus_verbs:передвинуть{}, // передвинуть на первое место rus_verbs:допускаться{}, // допускаться на полигон rus_verbs:задвинуть{}, // задвинуть на полку rus_verbs:повлиять{}, // повлиять на оценку rus_verbs:отбавлять{}, // отбавлять на осмотр rus_verbs:сбрасывать{}, // сбрасывать на землю rus_verbs:накинуться{}, // накинуться на случайных прохожих rus_verbs:пролить{}, // пролить на кожу руки rus_verbs:затащить{}, // затащить на сеновал rus_verbs:перебежать{}, // перебежать на сторону противника rus_verbs:наливать{}, // наливать на скатерть rus_verbs:пролезть{}, // пролезть на сцену rus_verbs:откладывать{}, // откладывать на черный день rus_verbs:распадаться{}, // распадаться на небольшие фрагменты rus_verbs:перечислить{}, // перечислить на счет rus_verbs:закачаться{}, // закачаться на верхний уровень rus_verbs:накрениться{}, // накрениться на правый борт rus_verbs:подвинуться{}, // подвинуться на один уровень rus_verbs:разнести{}, // разнести на мелкие кусочки rus_verbs:зажить{}, // зажить на широкую ногу rus_verbs:оглохнуть{}, // оглохнуть на правое ухо rus_verbs:посетовать{}, // посетовать на бюрократизм rus_verbs:уводить{}, // уводить на осмотр rus_verbs:ускакать{}, // ускакать на забег rus_verbs:посветить{}, // посветить на стену rus_verbs:разрываться{}, // разрываться на части rus_verbs:побросать{}, // побросать на землю rus_verbs:карабкаться{}, // карабкаться на скалу rus_verbs:нахлынуть{}, // нахлынуть на кого-то rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки rus_verbs:среагировать{}, // среагировать на сигнал rus_verbs:претендовать{}, // претендовать на приз rus_verbs:дунуть{}, // дунуть на одуванчик rus_verbs:переводиться{}, // переводиться на другую работу rus_verbs:перевезти{}, // перевезти на другую площадку rus_verbs:топать{}, // топать на урок rus_verbs:относить{}, // относить на склад rus_verbs:сбивать{}, // сбивать на землю rus_verbs:укладывать{}, // укладывать на спину rus_verbs:укатить{}, // укатить на отдых rus_verbs:убирать{}, // убирать на полку rus_verbs:опасть{}, // опасть на землю rus_verbs:ронять{}, // ронять на снег rus_verbs:пялиться{}, // пялиться на тело rus_verbs:глазеть{}, // глазеть на тело rus_verbs:снижаться{}, // снижаться на безопасную высоту rus_verbs:запрыгнуть{}, // запрыгнуть на платформу rus_verbs:разбиваться{}, // разбиваться на главы rus_verbs:сгодиться{}, // сгодиться на фарш rus_verbs:перескочить{}, // перескочить на другую страницу rus_verbs:нацелиться{}, // нацелиться на главную добычу rus_verbs:заезжать{}, // заезжать на бордюр rus_verbs:забираться{}, // забираться на крышу rus_verbs:проорать{}, // проорать на всё село rus_verbs:сбежаться{}, // сбежаться на шум rus_verbs:сменять{}, // сменять на хлеб rus_verbs:мотать{}, // мотать на ус rus_verbs:раскалываться{}, // раскалываться на две половинки rus_verbs:коситься{}, // коситься на режиссёра rus_verbs:плевать{}, // плевать на законы rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение rus_verbs:наставить{}, // наставить на путь истинный rus_verbs:завывать{}, // завывать на Луну rus_verbs:опаздывать{}, // опаздывать на совещание rus_verbs:залюбоваться{}, // залюбоваться на пейзаж rus_verbs:повергнуть{}, // повергнуть на землю rus_verbs:надвинуть{}, // надвинуть на лоб rus_verbs:стекаться{}, // стекаться на площадь rus_verbs:обозлиться{}, // обозлиться на тренера rus_verbs:оттянуть{}, // оттянуть на себя rus_verbs:истратить{}, // истратить на дешевых шлюх rus_verbs:вышвырнуть{}, // вышвырнуть на улицу rus_verbs:затолкать{}, // затолкать на верхнюю полку rus_verbs:заскочить{}, // заскочить на огонек rus_verbs:проситься{}, // проситься на улицу rus_verbs:натыкаться{}, // натыкаться на борщевик rus_verbs:обрушиваться{}, // обрушиваться на митингующих rus_verbs:переписать{}, // переписать на чистовик rus_verbs:переноситься{}, // переноситься на другое устройство rus_verbs:напроситься{}, // напроситься на обидный ответ rus_verbs:натягивать{}, // натягивать на ноги rus_verbs:кидаться{}, // кидаться на прохожих rus_verbs:откликаться{}, // откликаться на призыв rus_verbs:поспевать{}, // поспевать на балет rus_verbs:обратиться{}, // обратиться на кафедру rus_verbs:полюбоваться{}, // полюбоваться на бюст rus_verbs:таращиться{}, // таращиться на мустангов rus_verbs:напороться{}, // напороться на колючки rus_verbs:раздать{}, // раздать на руки rus_verbs:дивиться{}, // дивиться на танцовщиц rus_verbs:назначать{}, // назначать на ответственнейший пост rus_verbs:кидать{}, // кидать на балкон rus_verbs:нахлобучить{}, // нахлобучить на башку rus_verbs:увлекать{}, // увлекать на луг rus_verbs:ругнуться{}, // ругнуться на животину rus_verbs:переселиться{}, // переселиться на хутор rus_verbs:разрывать{}, // разрывать на части rus_verbs:утащить{}, // утащить на дерево rus_verbs:наставлять{}, // наставлять на путь rus_verbs:соблазнить{}, // соблазнить на обмен rus_verbs:накладывать{}, // накладывать на рану rus_verbs:набрести{}, // набрести на грибную поляну rus_verbs:наведываться{}, // наведываться на прежнюю работу rus_verbs:погулять{}, // погулять на чужие деньги rus_verbs:уклоняться{}, // уклоняться на два градуса влево rus_verbs:слезать{}, // слезать на землю rus_verbs:клевать{}, // клевать на мотыля // rus_verbs:назначаться{}, // назначаться на пост rus_verbs:напялить{}, // напялить на голову rus_verbs:натянуться{}, // натянуться на рамку rus_verbs:разгневаться{}, // разгневаться на придворных rus_verbs:эмигрировать{}, // эмигрировать на Кипр rus_verbs:накатить{}, // накатить на основу rus_verbs:пригнать{}, // пригнать на пастбище rus_verbs:обречь{}, // обречь на мучения rus_verbs:сокращаться{}, // сокращаться на четверть rus_verbs:оттеснить{}, // оттеснить на пристань rus_verbs:подбить{}, // подбить на аферу rus_verbs:заманить{}, // заманить на дерево инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик // деепричастие:пописав{ aux stress="поп^исать" }, rus_verbs:посходить{}, // посходить на перрон rus_verbs:налечь{}, // налечь на мясцо rus_verbs:отбирать{}, // отбирать на флот rus_verbs:нашептывать{}, // нашептывать на ухо rus_verbs:откладываться{}, // откладываться на будущее rus_verbs:залаять{}, // залаять на грабителя rus_verbs:настроиться{}, // настроиться на прием rus_verbs:разбивать{}, // разбивать на куски rus_verbs:пролиться{}, // пролиться на почву rus_verbs:сетовать{}, // сетовать на объективные трудности rus_verbs:подвезти{}, // подвезти на митинг rus_verbs:припереться{}, // припереться на праздник rus_verbs:подталкивать{}, // подталкивать на прыжок rus_verbs:прорываться{}, // прорываться на сцену rus_verbs:снижать{}, // снижать на несколько процентов rus_verbs:нацелить{}, // нацелить на танк rus_verbs:расколоть{}, // расколоть на два куска rus_verbs:увозить{}, // увозить на обкатку rus_verbs:оседать{}, // оседать на дно rus_verbs:съедать{}, // съедать на ужин rus_verbs:навлечь{}, // навлечь на себя rus_verbs:равняться{}, // равняться на лучших rus_verbs:сориентироваться{}, // сориентироваться на местности rus_verbs:снизить{}, // снизить на несколько процентов rus_verbs:перенестись{}, // перенестись на много лет назад rus_verbs:завезти{}, // завезти на склад rus_verbs:проложить{}, // проложить на гору rus_verbs:понадеяться{}, // понадеяться на удачу rus_verbs:заступить{}, // заступить на вахту rus_verbs:засеменить{}, // засеменить на выход rus_verbs:запирать{}, // запирать на ключ rus_verbs:скатываться{}, // скатываться на землю rus_verbs:дробить{}, // дробить на части rus_verbs:разваливаться{}, // разваливаться на кусочки rus_verbs:завозиться{}, // завозиться на склад rus_verbs:нанимать{}, // нанимать на дневную работу rus_verbs:поспеть{}, // поспеть на концерт rus_verbs:променять{}, // променять на сытость rus_verbs:переправить{}, // переправить на север rus_verbs:налетать{}, // налетать на силовое поле rus_verbs:затворить{}, // затворить на замок rus_verbs:подогнать{}, // подогнать на пристань rus_verbs:наехать{}, // наехать на камень rus_verbs:распевать{}, // распевать на разные голоса rus_verbs:разносить{}, // разносить на клочки rus_verbs:преувеличивать{}, // преувеличивать на много килограммов rus_verbs:хромать{}, // хромать на одну ногу rus_verbs:телеграфировать{}, // телеграфировать на базу rus_verbs:порезать{}, // порезать на лоскуты rus_verbs:порваться{}, // порваться на части rus_verbs:загонять{}, // загонять на дерево rus_verbs:отбывать{}, // отбывать на место службы rus_verbs:усаживаться{}, // усаживаться на трон rus_verbs:накопить{}, // накопить на квартиру rus_verbs:зыркнуть{}, // зыркнуть на визитера rus_verbs:копить{}, // копить на машину rus_verbs:помещать{}, // помещать на верхнюю грань rus_verbs:сползать{}, // сползать на снег rus_verbs:попроситься{}, // попроситься на улицу rus_verbs:перетащить{}, // перетащить на чердак rus_verbs:растащить{}, // растащить на сувениры rus_verbs:ниспадать{}, // ниспадать на землю rus_verbs:сфотографировать{}, // сфотографировать на память rus_verbs:нагонять{}, // нагонять на конкурентов страх rus_verbs:покушаться{}, // покушаться на понтифика rus_verbs:покуситься{}, rus_verbs:наняться{}, // наняться на службу rus_verbs:просачиваться{}, // просачиваться на поверхность rus_verbs:пускаться{}, // пускаться на ветер rus_verbs:отваживаться{}, // отваживаться на прыжок rus_verbs:досадовать{}, // досадовать на объективные трудности rus_verbs:унестись{}, // унестись на небо rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов rus_verbs:насадить{}, // насадить на копьё rus_verbs:нагрянуть{}, // нагрянуть на праздник rus_verbs:зашвырнуть{}, // зашвырнуть на полку rus_verbs:грешить{}, // грешить на постояльцев rus_verbs:просочиться{}, // просочиться на поверхность rus_verbs:надоумить{}, // надоумить на глупость rus_verbs:намотать{}, // намотать на шпиндель rus_verbs:замкнуть{}, // замкнуть на корпус rus_verbs:цыкнуть{}, // цыкнуть на детей rus_verbs:переворачиваться{}, // переворачиваться на спину rus_verbs:соваться{}, // соваться на площать rus_verbs:отлучиться{}, // отлучиться на обед rus_verbs:пенять{}, // пенять на себя rus_verbs:нарезать{}, // нарезать на ломтики rus_verbs:поставлять{}, // поставлять на Кипр rus_verbs:залезать{}, // залезать на балкон rus_verbs:отлучаться{}, // отлучаться на обед rus_verbs:сбиваться{}, // сбиваться на шаг rus_verbs:таращить{}, // таращить глаза на вошедшего rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню rus_verbs:опережать{}, // опережать на пару сантиметров rus_verbs:переставить{}, // переставить на стол rus_verbs:раздирать{}, // раздирать на части rus_verbs:затвориться{}, // затвориться на засовы rus_verbs:материться{}, // материться на кого-то rus_verbs:наскочить{}, // наскочить на риф rus_verbs:набираться{}, // набираться на борт rus_verbs:покрикивать{}, // покрикивать на помощников rus_verbs:заменяться{}, // заменяться на более новый rus_verbs:подсадить{}, // подсадить на верхнюю полку rus_verbs:проковылять{}, // проковылять на кухню rus_verbs:прикатить{}, // прикатить на старт rus_verbs:залететь{}, // залететь на чужую территорию rus_verbs:загрузить{}, // загрузить на конвейер rus_verbs:уплывать{}, // уплывать на материк rus_verbs:опозорить{}, // опозорить на всю деревню rus_verbs:провоцировать{}, // провоцировать на ответную агрессию rus_verbs:забивать{}, // забивать на учебу rus_verbs:набегать{}, // набегать на прибрежные деревни rus_verbs:запираться{}, // запираться на ключ rus_verbs:фотографировать{}, // фотографировать на мыльницу rus_verbs:подымать{}, // подымать на недосягаемую высоту rus_verbs:съезжаться{}, // съезжаться на симпозиум rus_verbs:отвлекаться{}, // отвлекаться на игру rus_verbs:проливать{}, // проливать на брюки rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца rus_verbs:уползти{}, // уползти на вершину холма rus_verbs:переместить{}, // переместить на вторую палубу rus_verbs:превысить{}, // превысить на несколько метров rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку rus_verbs:спровоцировать{}, // спровоцировать на бросок rus_verbs:сместиться{}, // сместиться на соседнюю клетку rus_verbs:заготовить{}, // заготовить на зиму rus_verbs:плеваться{}, // плеваться на пол rus_verbs:переселить{}, // переселить на север rus_verbs:напирать{}, // напирать на дверь rus_verbs:переезжать{}, // переезжать на другой этаж rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров rus_verbs:трогаться{}, // трогаться на красный свет rus_verbs:надвинуться{}, // надвинуться на глаза rus_verbs:засмотреться{}, // засмотреться на купальники rus_verbs:убыть{}, // убыть на фронт rus_verbs:передвигать{}, // передвигать на второй уровень rus_verbs:отвозить{}, // отвозить на свалку rus_verbs:обрекать{}, // обрекать на гибель rus_verbs:записываться{}, // записываться на танцы rus_verbs:настраивать{}, // настраивать на другой диапазон rus_verbs:переписывать{}, // переписывать на диск rus_verbs:израсходовать{}, // израсходовать на гонки rus_verbs:обменять{}, // обменять на перспективного игрока rus_verbs:трубить{}, // трубить на всю округу rus_verbs:набрасываться{}, // набрасываться на жертву rus_verbs:чихать{}, // чихать на правила rus_verbs:наваливаться{}, // наваливаться на рычаг rus_verbs:сподобиться{}, // сподобиться на повторный анализ rus_verbs:намазать{}, // намазать на хлеб rus_verbs:прореагировать{}, // прореагировать на вызов rus_verbs:зачислить{}, // зачислить на факультет rus_verbs:наведаться{}, // наведаться на склад rus_verbs:откидываться{}, // откидываться на спинку кресла rus_verbs:захромать{}, // захромать на левую ногу rus_verbs:перекочевать{}, // перекочевать на другой берег rus_verbs:накатываться{}, // накатываться на песчаный берег rus_verbs:приостановить{}, // приостановить на некоторое время rus_verbs:запрятать{}, // запрятать на верхнюю полочку rus_verbs:прихрамывать{}, // прихрамывать на правую ногу rus_verbs:упорхнуть{}, // упорхнуть на свободу rus_verbs:расстегивать{}, // расстегивать на пальто rus_verbs:напуститься{}, // напуститься на бродягу rus_verbs:накатывать{}, // накатывать на оригинал rus_verbs:наезжать{}, // наезжать на простофилю rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека rus_verbs:отрядить{}, // отрядить на починку rus_verbs:положиться{}, // положиться на главаря rus_verbs:опрокидывать{}, // опрокидывать на голову rus_verbs:поторапливаться{}, // поторапливаться на рейс rus_verbs:налагать{}, // налагать на заемщика rus_verbs:скопировать{}, // скопировать на диск rus_verbs:опадать{}, // опадать на землю rus_verbs:купиться{}, // купиться на посулы rus_verbs:гневаться{}, // гневаться на слуг rus_verbs:слететься{}, // слететься на раздачу rus_verbs:убавить{}, // убавить на два уровня rus_verbs:спихнуть{}, // спихнуть на соседа rus_verbs:накричать{}, // накричать на ребенка rus_verbs:приберечь{}, // приберечь на ужин rus_verbs:приклеить{}, // приклеить на ветровое стекло rus_verbs:ополчиться{}, // ополчиться на посредников rus_verbs:тратиться{}, // тратиться на сувениры rus_verbs:слетаться{}, // слетаться на свет rus_verbs:доставляться{}, // доставляться на базу rus_verbs:поплевать{}, // поплевать на руки rus_verbs:огрызаться{}, // огрызаться на замечание rus_verbs:попереться{}, // попереться на рынок rus_verbs:растягиваться{}, // растягиваться на полу rus_verbs:повергать{}, // повергать на землю rus_verbs:ловиться{}, // ловиться на мотыля rus_verbs:наседать{}, // наседать на обороняющихся rus_verbs:развалить{}, // развалить на кирпичи rus_verbs:разломить{}, // разломить на несколько частей rus_verbs:примерить{}, // примерить на себя rus_verbs:лепиться{}, // лепиться на стену rus_verbs:скопить{}, // скопить на старость rus_verbs:затратить{}, // затратить на ликвидацию последствий rus_verbs:притащиться{}, // притащиться на гулянку rus_verbs:осерчать{}, // осерчать на прислугу rus_verbs:натравить{}, // натравить на медведя rus_verbs:ссыпать{}, // ссыпать на землю rus_verbs:подвозить{}, // подвозить на пристань rus_verbs:мобилизовать{}, // мобилизовать на сборы rus_verbs:смотаться{}, // смотаться на работу rus_verbs:заглядеться{}, // заглядеться на девчонок rus_verbs:таскаться{}, // таскаться на работу rus_verbs:разгружать{}, // разгружать на транспортер rus_verbs:потреблять{}, // потреблять на кондиционирование инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу деепричастие:сгоняв{}, rus_verbs:посылаться{}, // посылаться на разведку rus_verbs:окрыситься{}, // окрыситься на кого-то rus_verbs:отлить{}, // отлить на сковороду rus_verbs:шикнуть{}, // шикнуть на детишек rus_verbs:уповать{}, // уповать на бескорысную помощь rus_verbs:класться{}, // класться на стол rus_verbs:поковылять{}, // поковылять на выход rus_verbs:навевать{}, // навевать на собравшихся скуку rus_verbs:накладываться{}, // накладываться на грунтовку rus_verbs:наноситься{}, // наноситься на чистую кожу // rus_verbs:запланировать{}, // запланировать на среду rus_verbs:кувыркнуться{}, // кувыркнуться на землю rus_verbs:гавкнуть{}, // гавкнуть на хозяина rus_verbs:перестроиться{}, // перестроиться на новый лад rus_verbs:расходоваться{}, // расходоваться на образование rus_verbs:дуться{}, // дуться на бабушку rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол rus_verbs:издаться{}, // издаться на деньги спонсоров rus_verbs:смещаться{}, // смещаться на несколько миллиметров rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу rus_verbs:пикировать{}, // пикировать на окопы rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей rus_verbs:зудить{}, // зудить на ухо rus_verbs:подразделяться{}, // подразделяться на группы rus_verbs:изливаться{}, // изливаться на землю rus_verbs:помочиться{}, // помочиться на траву rus_verbs:примерять{}, // примерять на себя rus_verbs:разрядиться{}, // разрядиться на землю rus_verbs:мотнуться{}, // мотнуться на крышу rus_verbs:налегать{}, // налегать на весла rus_verbs:зацокать{}, // зацокать на куриц rus_verbs:наниматься{}, // наниматься на корабль rus_verbs:сплевывать{}, // сплевывать на землю rus_verbs:настучать{}, // настучать на саботажника rus_verbs:приземляться{}, // приземляться на брюхо rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу rus_verbs:серчать{}, // серчать на нерасторопную помощницу rus_verbs:сваливать{}, // сваливать на подоконник rus_verbs:засобираться{}, // засобираться на работу rus_verbs:распилить{}, // распилить на одинаковые бруски //rus_verbs:умножать{}, // умножать на константу rus_verbs:копировать{}, // копировать на диск rus_verbs:накрутить{}, // накрутить на руку rus_verbs:навалить{}, // навалить на телегу rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль rus_verbs:шлепаться{}, // шлепаться на бетон rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение rus_verbs:посягнуть{}, // посягнуть на святое rus_verbs:разменять{}, // разменять на мелочь rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции rus_verbs:усаживать{}, // усаживать на скамейку rus_verbs:натаскать{}, // натаскать на поиск наркотиков rus_verbs:зашикать{}, // зашикать на кошку rus_verbs:разломать{}, // разломать на равные части rus_verbs:приглашаться{}, // приглашаться на сцену rus_verbs:присягать{}, // присягать на верность rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку rus_verbs:расщедриться{}, // расщедриться на новый компьютер rus_verbs:насесть{}, // насесть на двоечников rus_verbs:созывать{}, // созывать на собрание rus_verbs:позариться{}, // позариться на чужое добро rus_verbs:перекидываться{}, // перекидываться на соседние здания rus_verbs:наползать{}, // наползать на неповрежденную ткань rus_verbs:изрубить{}, // изрубить на мелкие кусочки rus_verbs:наворачиваться{}, // наворачиваться на глаза rus_verbs:раскричаться{}, // раскричаться на всю округу rus_verbs:переползти{}, // переползти на светлую сторону rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию rus_verbs:мочиться{}, // мочиться на трупы убитых врагов rus_verbs:радировать{}, // радировать на базу rus_verbs:промотать{}, // промотать на начало rus_verbs:заснять{}, // заснять на видео rus_verbs:подбивать{}, // подбивать на матч-реванш rus_verbs:наплевать{}, // наплевать на справедливость rus_verbs:подвывать{}, // подвывать на луну rus_verbs:расплескать{}, // расплескать на пол rus_verbs:польститься{}, // польститься на бесплатный сыр rus_verbs:помчать{}, // помчать на работу rus_verbs:съезжать{}, // съезжать на обочину rus_verbs:нашептать{}, // нашептать кому-то на ухо rus_verbs:наклеить{}, // наклеить на доску объявлений rus_verbs:завозить{}, // завозить на склад rus_verbs:заявляться{}, // заявляться на любимую работу rus_verbs:наглядеться{}, // наглядеться на воробьев rus_verbs:хлопнуться{}, // хлопнуться на живот rus_verbs:забредать{}, // забредать на поляну rus_verbs:посягать{}, // посягать на исконные права собственности rus_verbs:сдвигать{}, // сдвигать на одну позицию rus_verbs:спрыгивать{}, // спрыгивать на землю rus_verbs:сдвигаться{}, // сдвигаться на две позиции rus_verbs:разделать{}, // разделать на орехи rus_verbs:разлагать{}, // разлагать на элементарные элементы rus_verbs:обрушивать{}, // обрушивать на головы врагов rus_verbs:натечь{}, // натечь на пол rus_verbs:политься{}, // вода польется на землю rus_verbs:успеть{}, // Они успеют на поезд. инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш }, деепричастие:мигрируя{}, инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш }, деепричастие:мигрировав{}, rus_verbs:двинуться{}, // Мы скоро двинемся на дачу. rus_verbs:подойти{}, // Он не подойдёт на должность секретаря. rus_verbs:потянуть{}, // Он не потянет на директора. rus_verbs:тянуть{}, // Он не тянет на директора. rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:жаловаться{}, // Он жалуется на нездоровье. rus_verbs:издать{}, // издать на деньги спонсоров rus_verbs:показаться{}, // показаться на глаза rus_verbs:высаживать{}, // высаживать на необитаемый остров rus_verbs:вознестись{}, // вознестись на самую вершину славы rus_verbs:залить{}, // залить на youtube rus_verbs:закачать{}, // закачать на youtube rus_verbs:сыграть{}, // сыграть на деньги rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных глагол:экстраполироваться{ вид:несоверш}, инфинитив:экстраполироваться{ вид:соверш}, глагол:экстраполироваться{ вид:соверш}, деепричастие:экстраполируясь{}, инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы глагол:акцентировать{вид:соверш}, инфинитив:акцентировать{вид:несоверш}, глагол:акцентировать{вид:несоверш}, прилагательное:акцентировавший{вид:несоверш}, //прилагательное:акцентировавший{вид:соверш}, прилагательное:акцентирующий{}, деепричастие:акцентировав{}, деепричастие:акцентируя{}, rus_verbs:бабахаться{}, // он бабахался на пол rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина rus_verbs:бахаться{}, // Наездники бахались на землю rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю rus_verbs:благословить{}, // батюшка благословил отрока на подвиг rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг rus_verbs:блевануть{}, // Он блеванул на землю rus_verbs:блевать{}, // Он блюет на землю rus_verbs:бухнуться{}, // Наездник бухнулся на землю rus_verbs:валить{}, // Ветер валил деревья на землю rus_verbs:спилить{}, // Спиленное дерево валится на землю rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес rus_verbs:вестись{}, // Не ведись на эти уловки! rus_verbs:вешать{}, // Гости вешают одежду на вешалку rus_verbs:вешаться{}, // Одежда вешается на вешалки rus_verbs:вещать{}, // радиостанция вещает на всю страну rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм rus_verbs:взбредать{}, // Что иногда взбредает на ум rus_verbs:взбрести{}, // Что-то взбрело на ум rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи rus_verbs:взглянуть{}, // Кошка взглянула на мышку rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух rus_verbs:взобраться{}, // Туристы взобрались на гору rus_verbs:взойти{}, // Туристы взошли на гору rus_verbs:взъесться{}, // Отец взъелся на непутевого сына rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка rus_verbs:водворить{}, // водворить нарушителя на место rus_verbs:водвориться{}, // водвориться на свое место rus_verbs:водворять{}, // водворять вещь на свое место rus_verbs:водворяться{}, // водворяться на свое место rus_verbs:водружать{}, // водружать флаг на флагшток rus_verbs:водружаться{}, // Флаг водружается на флагшток rus_verbs:водрузить{}, // водрузить флаг на флагшток rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы rus_verbs:воздействовать{}, // Излучение воздействует на кожу rus_verbs:воззреть{}, // воззреть на поле боя rus_verbs:воззриться{}, // воззриться на поле боя rus_verbs:возить{}, // возить туристов на гору rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу rus_verbs:возлагаться{}, // Ответственность возлагается на начальство rus_verbs:возлечь{}, // возлечь на лежанку rus_verbs:возложить{}, // возложить цветы на могилу поэта rus_verbs:вознести{}, // вознести кого-то на вершину славы rus_verbs:возноситься{}, // возносится на вершину успеха rus_verbs:возносить{}, // возносить счастливчика на вершину успеха rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж rus_verbs:подняться{}, // Мы поднялись на восьмой этаж rus_verbs:вонять{}, // Кусок сыра воняет на всю округу rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги rus_verbs:ворчать{}, // Старый пес ворчит на прохожих rus_verbs:воспринимать{}, // воспринимать сообщение на слух rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух rus_verbs:воспринять{}, // воспринять сообщение на слух rus_verbs:восприняться{}, // восприняться на слух rus_verbs:воссесть{}, // Коля воссел на трон rus_verbs:вправить{}, // вправить мозг на место rus_verbs:вправлять{}, // вправлять мозги на место rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:врубать{}, // врубать на полную мощность rus_verbs:врубить{}, // врубить на полную мощность rus_verbs:врубиться{}, // врубиться на полную мощность rus_verbs:врываться{}, // врываться на собрание rus_verbs:вскарабкаться{}, // вскарабкаться на утёс rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс rus_verbs:вскочить{}, // вскочить на ноги rus_verbs:всплывать{}, // всплывать на поверхность воды rus_verbs:всплыть{}, // всплыть на поверхность воды rus_verbs:вспрыгивать{}, // вспрыгивать на платформу rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу rus_verbs:встать{}, // встать на защиту чести и достоинства rus_verbs:вторгаться{}, // вторгаться на чужую территорию rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию rus_verbs:въезжать{}, // въезжать на пандус rus_verbs:наябедничать{}, // наябедничать на соседа по парте rus_verbs:выблевать{}, // выблевать завтрак на пол rus_verbs:выблеваться{}, // выблеваться на пол rus_verbs:выблевывать{}, // выблевывать завтрак на пол rus_verbs:выблевываться{}, // выблевываться на пол rus_verbs:вывезти{}, // вывезти мусор на свалку rus_verbs:вывесить{}, // вывесить белье на просушку rus_verbs:вывести{}, // вывести собаку на прогулку rus_verbs:вывешивать{}, // вывешивать белье на веревку rus_verbs:вывозить{}, // вывозить детей на природу rus_verbs:вызывать{}, // Начальник вызывает на ковер rus_verbs:выйти{}, // выйти на свободу rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение rus_verbs:выливать{}, // выливать на землю rus_verbs:выливаться{}, // выливаться на землю rus_verbs:вылить{}, // вылить жидкость на землю rus_verbs:вылиться{}, // Топливо вылилось на землю rus_verbs:выложить{}, // выложить на берег rus_verbs:выменивать{}, // выменивать золото на хлеб rus_verbs:вымениваться{}, // Золото выменивается на хлеб rus_verbs:выменять{}, // выменять золото на хлеб rus_verbs:выпадать{}, // снег выпадает на землю rus_verbs:выплевывать{}, // выплевывать на землю rus_verbs:выплевываться{}, // выплевываться на землю rus_verbs:выплескать{}, // выплескать на землю rus_verbs:выплескаться{}, // выплескаться на землю rus_verbs:выплескивать{}, // выплескивать на землю rus_verbs:выплескиваться{}, // выплескиваться на землю rus_verbs:выплывать{}, // выплывать на поверхность rus_verbs:выплыть{}, // выплыть на поверхность rus_verbs:выплюнуть{}, // выплюнуть на пол rus_verbs:выползать{}, // выползать на свежий воздух rus_verbs:выпроситься{}, // выпроситься на улицу rus_verbs:выпрыгивать{}, // выпрыгивать на свободу rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон rus_verbs:выпускать{}, // выпускать на свободу rus_verbs:выпустить{}, // выпустить на свободу rus_verbs:выпучивать{}, // выпучивать на кого-то глаза rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то rus_verbs:выпучить{}, // выпучить глаза на кого-то rus_verbs:выпучиться{}, // выпучиться на кого-то rus_verbs:выронить{}, // выронить на землю rus_verbs:высадить{}, // высадить на берег rus_verbs:высадиться{}, // высадиться на берег rus_verbs:высаживаться{}, // высаживаться на остров rus_verbs:выскальзывать{}, // выскальзывать на землю rus_verbs:выскочить{}, // выскочить на сцену rus_verbs:высморкаться{}, // высморкаться на землю rus_verbs:высморкнуться{}, // высморкнуться на землю rus_verbs:выставить{}, // выставить на всеобщее обозрение rus_verbs:выставиться{}, // выставиться на всеобщее обозрение rus_verbs:выставлять{}, // выставлять на всеобщее обозрение rus_verbs:выставляться{}, // выставляться на всеобщее обозрение инфинитив:высыпать{вид:соверш}, // высыпать на землю инфинитив:высыпать{вид:несоверш}, глагол:высыпать{вид:соверш}, глагол:высыпать{вид:несоверш}, деепричастие:высыпав{}, деепричастие:высыпая{}, прилагательное:высыпавший{вид:соверш}, //++прилагательное:высыпавший{вид:несоверш}, прилагательное:высыпающий{вид:несоверш}, rus_verbs:высыпаться{}, // высыпаться на землю rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя rus_verbs:вытаращиваться{}, // вытаращиваться на медведя rus_verbs:вытаращить{}, // вытаращить глаза на медведя rus_verbs:вытаращиться{}, // вытаращиться на медведя rus_verbs:вытекать{}, // вытекать на землю rus_verbs:вытечь{}, // вытечь на землю rus_verbs:выучиваться{}, // выучиваться на кого-то rus_verbs:выучиться{}, // выучиться на кого-то rus_verbs:посмотреть{}, // посмотреть на экран rus_verbs:нашить{}, // нашить что-то на одежду rus_verbs:придти{}, // придти на помощь кому-то инфинитив:прийти{}, // прийти на помощь кому-то глагол:прийти{}, деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты. rus_verbs:поднять{}, // поднять на вершину rus_verbs:согласиться{}, // согласиться на ничью rus_verbs:послать{}, // послать на фронт rus_verbs:слать{}, // слать на фронт rus_verbs:надеяться{}, // надеяться на лучшее rus_verbs:крикнуть{}, // крикнуть на шалунов rus_verbs:пройти{}, // пройти на пляж rus_verbs:прислать{}, // прислать на экспертизу rus_verbs:жить{}, // жить на подачки rus_verbs:становиться{}, // становиться на ноги rus_verbs:наслать{}, // наслать на кого-то rus_verbs:принять{}, // принять на заметку rus_verbs:собираться{}, // собираться на экзамен rus_verbs:оставить{}, // оставить на всякий случай rus_verbs:звать{}, // звать на помощь rus_verbs:направиться{}, // направиться на прогулку rus_verbs:отвечать{}, // отвечать на звонки rus_verbs:отправиться{}, // отправиться на прогулку rus_verbs:поставить{}, // поставить на пол rus_verbs:обернуться{}, // обернуться на зов rus_verbs:отозваться{}, // отозваться на просьбу rus_verbs:закричать{}, // закричать на собаку rus_verbs:опустить{}, // опустить на землю rus_verbs:принести{}, // принести на пляж свой жезлонг rus_verbs:указать{}, // указать на дверь rus_verbs:ходить{}, // ходить на занятия rus_verbs:уставиться{}, // уставиться на листок rus_verbs:приходить{}, // приходить на экзамен rus_verbs:махнуть{}, // махнуть на пляж rus_verbs:явиться{}, // явиться на допрос rus_verbs:оглянуться{}, // оглянуться на дорогу rus_verbs:уехать{}, // уехать на заработки rus_verbs:повести{}, // повести на штурм rus_verbs:опуститься{}, // опуститься на колени //rus_verbs:передать{}, // передать на проверку rus_verbs:побежать{}, // побежать на занятия rus_verbs:прибыть{}, // прибыть на место службы rus_verbs:кричать{}, // кричать на медведя rus_verbs:стечь{}, // стечь на землю rus_verbs:обратить{}, // обратить на себя внимание rus_verbs:подать{}, // подать на пропитание rus_verbs:привести{}, // привести на съемки rus_verbs:испытывать{}, // испытывать на животных rus_verbs:перевести{}, // перевести на жену rus_verbs:купить{}, // купить на заемные деньги rus_verbs:собраться{}, // собраться на встречу rus_verbs:заглянуть{}, // заглянуть на огонёк rus_verbs:нажать{}, // нажать на рычаг rus_verbs:поспешить{}, // поспешить на праздник rus_verbs:перейти{}, // перейти на русский язык rus_verbs:поверить{}, // поверить на честное слово rus_verbs:глянуть{}, // глянуть на обложку rus_verbs:зайти{}, // зайти на огонёк rus_verbs:проходить{}, // проходить на сцену rus_verbs:глядеть{}, // глядеть на актрису //rus_verbs:решиться{}, // решиться на прыжок rus_verbs:пригласить{}, // пригласить на танец rus_verbs:позвать{}, // позвать на экзамен rus_verbs:усесться{}, // усесться на стул rus_verbs:поступить{}, // поступить на математический факультет rus_verbs:лечь{}, // лечь на живот rus_verbs:потянуться{}, // потянуться на юг rus_verbs:присесть{}, // присесть на корточки rus_verbs:наступить{}, // наступить на змею rus_verbs:заорать{}, // заорать на попрошаек rus_verbs:надеть{}, // надеть на голову rus_verbs:поглядеть{}, // поглядеть на девчонок rus_verbs:принимать{}, // принимать на гарантийное обслуживание rus_verbs:привезти{}, // привезти на испытания rus_verbs:рухнуть{}, // рухнуть на асфальт rus_verbs:пускать{}, // пускать на корм rus_verbs:отвести{}, // отвести на приём rus_verbs:отправить{}, // отправить на утилизацию rus_verbs:двигаться{}, // двигаться на восток rus_verbs:нести{}, // нести на пляж rus_verbs:падать{}, // падать на руки rus_verbs:откинуться{}, // откинуться на спинку кресла rus_verbs:рявкнуть{}, // рявкнуть на детей rus_verbs:получать{}, // получать на проживание rus_verbs:полезть{}, // полезть на рожон rus_verbs:направить{}, // направить на дообследование rus_verbs:приводить{}, // приводить на проверку rus_verbs:потребоваться{}, // потребоваться на замену rus_verbs:кинуться{}, // кинуться на нападавшего rus_verbs:учиться{}, // учиться на токаря rus_verbs:приподнять{}, // приподнять на один метр rus_verbs:налить{}, // налить на стол rus_verbs:играть{}, // играть на деньги rus_verbs:рассчитывать{}, // рассчитывать на подмогу rus_verbs:шепнуть{}, // шепнуть на ухо rus_verbs:швырнуть{}, // швырнуть на землю rus_verbs:прыгнуть{}, // прыгнуть на оленя rus_verbs:предлагать{}, // предлагать на выбор rus_verbs:садиться{}, // садиться на стул rus_verbs:лить{}, // лить на землю rus_verbs:испытать{}, // испытать на животных rus_verbs:фыркнуть{}, // фыркнуть на детеныша rus_verbs:годиться{}, // мясо годится на фарш rus_verbs:проверить{}, // проверить высказывание на истинность rus_verbs:откликнуться{}, // откликнуться на призывы rus_verbs:полагаться{}, // полагаться на интуицию rus_verbs:покоситься{}, // покоситься на соседа rus_verbs:повесить{}, // повесить на гвоздь инфинитив:походить{вид:соверш}, // походить на занятия глагол:походить{вид:соверш}, деепричастие:походив{}, прилагательное:походивший{}, rus_verbs:помчаться{}, // помчаться на экзамен rus_verbs:ставить{}, // ставить на контроль rus_verbs:свалиться{}, // свалиться на землю rus_verbs:валиться{}, // валиться на землю rus_verbs:подарить{}, // подарить на день рожденья rus_verbs:сбежать{}, // сбежать на необитаемый остров rus_verbs:стрелять{}, // стрелять на поражение rus_verbs:обращать{}, // обращать на себя внимание rus_verbs:наступать{}, // наступать на те же грабли rus_verbs:сбросить{}, // сбросить на землю rus_verbs:обидеться{}, // обидеться на друга rus_verbs:устроиться{}, // устроиться на стажировку rus_verbs:погрузиться{}, // погрузиться на большую глубину rus_verbs:течь{}, // течь на землю rus_verbs:отбросить{}, // отбросить на землю rus_verbs:метать{}, // метать на дно rus_verbs:пустить{}, // пустить на переплавку rus_verbs:прожить{}, // прожить на пособие rus_verbs:полететь{}, // полететь на континент rus_verbs:пропустить{}, // пропустить на сцену rus_verbs:указывать{}, // указывать на ошибку rus_verbs:наткнуться{}, // наткнуться на клад rus_verbs:рвануть{}, // рвануть на юг rus_verbs:ступать{}, // ступать на землю rus_verbs:спрыгнуть{}, // спрыгнуть на берег rus_verbs:заходить{}, // заходить на огонёк rus_verbs:нырнуть{}, // нырнуть на глубину rus_verbs:рвануться{}, // рвануться на свободу rus_verbs:натянуть{}, // натянуть на голову rus_verbs:забраться{}, // забраться на стол rus_verbs:помахать{}, // помахать на прощание rus_verbs:содержать{}, // содержать на спонсорскую помощь rus_verbs:приезжать{}, // приезжать на праздники rus_verbs:проникнуть{}, // проникнуть на территорию rus_verbs:подъехать{}, // подъехать на митинг rus_verbs:устремиться{}, // устремиться на волю rus_verbs:посадить{}, // посадить на стул rus_verbs:ринуться{}, // ринуться на голкипера rus_verbs:подвигнуть{}, // подвигнуть на подвиг rus_verbs:отдавать{}, // отдавать на перевоспитание rus_verbs:отложить{}, // отложить на черный день rus_verbs:убежать{}, // убежать на танцы rus_verbs:поднимать{}, // поднимать на верхний этаж rus_verbs:переходить{}, // переходить на цифровой сигнал rus_verbs:отослать{}, // отослать на переаттестацию rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола rus_verbs:назначить{}, // назначить на должность rus_verbs:осесть{}, // осесть на дно rus_verbs:торопиться{}, // торопиться на экзамен rus_verbs:менять{}, // менять на еду rus_verbs:доставить{}, // доставить на шестой этаж rus_verbs:заслать{}, // заслать на проверку rus_verbs:дуть{}, // дуть на воду rus_verbs:сослать{}, // сослать на каторгу rus_verbs:останавливаться{}, // останавливаться на отдых rus_verbs:сдаваться{}, // сдаваться на милость победителя rus_verbs:сослаться{}, // сослаться на презумпцию невиновности rus_verbs:рассердиться{}, // рассердиться на дочь rus_verbs:кинуть{}, // кинуть на землю rus_verbs:расположиться{}, // расположиться на ночлег rus_verbs:осмелиться{}, // осмелиться на подлог rus_verbs:шептать{}, // шептать на ушко rus_verbs:уронить{}, // уронить на землю rus_verbs:откинуть{}, // откинуть на спинку кресла rus_verbs:перенести{}, // перенести на рабочий стол rus_verbs:сдаться{}, // сдаться на милость победителя rus_verbs:светить{}, // светить на дорогу rus_verbs:мчаться{}, // мчаться на бал rus_verbs:нестись{}, // нестись на свидание rus_verbs:поглядывать{}, // поглядывать на экран rus_verbs:орать{}, // орать на детей rus_verbs:уложить{}, // уложить на лопатки rus_verbs:решаться{}, // решаться на поступок rus_verbs:попадать{}, // попадать на карандаш rus_verbs:сплюнуть{}, // сплюнуть на землю rus_verbs:снимать{}, // снимать на телефон rus_verbs:опоздать{}, // опоздать на работу rus_verbs:посылать{}, // посылать на проверку rus_verbs:погнать{}, // погнать на пастбище rus_verbs:поступать{}, // поступать на кибернетический факультет rus_verbs:спускаться{}, // спускаться на уровень моря rus_verbs:усадить{}, // усадить на диван rus_verbs:проиграть{}, // проиграть на спор rus_verbs:прилететь{}, // прилететь на фестиваль rus_verbs:повалиться{}, // повалиться на спину rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина rus_verbs:задавать{}, // задавать на выходные rus_verbs:запасть{}, // запасть на девочку rus_verbs:лезть{}, // лезть на забор rus_verbs:потащить{}, // потащить на выборы rus_verbs:направляться{}, // направляться на экзамен rus_verbs:определять{}, // определять на вкус rus_verbs:поползти{}, // поползти на стену rus_verbs:поплыть{}, // поплыть на берег rus_verbs:залезть{}, // залезть на яблоню rus_verbs:сдать{}, // сдать на мясокомбинат rus_verbs:приземлиться{}, // приземлиться на дорогу rus_verbs:лаять{}, // лаять на прохожих rus_verbs:перевернуть{}, // перевернуть на бок rus_verbs:ловить{}, // ловить на живца rus_verbs:отнести{}, // отнести животное на хирургический стол rus_verbs:плюнуть{}, // плюнуть на условности rus_verbs:передавать{}, // передавать на проверку rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали инфинитив:рассыпаться{вид:соверш}, глагол:рассыпаться{вид:несоверш}, глагол:рассыпаться{вид:соверш}, деепричастие:рассыпавшись{}, деепричастие:рассыпаясь{}, прилагательное:рассыпавшийся{вид:несоверш}, прилагательное:рассыпавшийся{вид:соверш}, прилагательное:рассыпающийся{}, rus_verbs:зарычать{}, // Медведица зарычала на медвежонка rus_verbs:призвать{}, // призвать на сборы rus_verbs:увезти{}, // увезти на дачу rus_verbs:содержаться{}, // содержаться на пожертвования rus_verbs:навести{}, // навести на скопление телескоп rus_verbs:отправляться{}, // отправляться на утилизацию rus_verbs:улечься{}, // улечься на животик rus_verbs:налететь{}, // налететь на препятствие rus_verbs:перевернуться{}, // перевернуться на спину rus_verbs:улететь{}, // улететь на родину rus_verbs:ложиться{}, // ложиться на бок rus_verbs:класть{}, // класть на место rus_verbs:отреагировать{}, // отреагировать на выступление rus_verbs:доставлять{}, // доставлять на дом rus_verbs:отнять{}, // отнять на благо правящей верхушки rus_verbs:ступить{}, // ступить на землю rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы rus_verbs:унести{}, // унести на работу rus_verbs:сходить{}, // сходить на концерт rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги rus_verbs:соскочить{}, // соскочить на землю rus_verbs:пожаловаться{}, // пожаловаться на соседей rus_verbs:тащить{}, // тащить на замену rus_verbs:замахать{}, // замахать руками на паренька rus_verbs:заглядывать{}, // заглядывать на обед rus_verbs:соглашаться{}, // соглашаться на равный обмен rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик rus_verbs:увести{}, // увести на осмотр rus_verbs:успевать{}, // успевать на контрольную работу rus_verbs:опрокинуть{}, // опрокинуть на себя rus_verbs:подавать{}, // подавать на апелляцию rus_verbs:прибежать{}, // прибежать на вокзал rus_verbs:отшвырнуть{}, // отшвырнуть на замлю rus_verbs:привлекать{}, // привлекать на свою сторону rus_verbs:опереться{}, // опереться на палку rus_verbs:перебраться{}, // перебраться на маленький островок rus_verbs:уговорить{}, // уговорить на новые траты rus_verbs:гулять{}, // гулять на спонсорские деньги rus_verbs:переводить{}, // переводить на другой путь rus_verbs:заколебаться{}, // заколебаться на один миг rus_verbs:зашептать{}, // зашептать на ушко rus_verbs:привстать{}, // привстать на цыпочки rus_verbs:хлынуть{}, // хлынуть на берег rus_verbs:наброситься{}, // наброситься на еду rus_verbs:напасть{}, // повстанцы, напавшие на конвой rus_verbs:убрать{}, // книга, убранная на полку rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию rus_verbs:засматриваться{}, // засматриваться на девчонок rus_verbs:застегнуться{}, // застегнуться на все пуговицы rus_verbs:провериться{}, // провериться на заболевания rus_verbs:проверяться{}, // проверяться на заболевания rus_verbs:тестировать{}, // тестировать на профпригодность rus_verbs:протестировать{}, // протестировать на профпригодность rus_verbs:уходить{}, // отец, уходящий на работу rus_verbs:налипнуть{}, // снег, налипший на провода rus_verbs:налипать{}, // снег, налипающий на провода rus_verbs:улетать{}, // Многие птицы улетают осенью на юг. rus_verbs:поехать{}, // она поехала на встречу с заказчиком rus_verbs:переключать{}, // переключать на резервную линию rus_verbs:переключаться{}, // переключаться на резервную линию rus_verbs:подписаться{}, // подписаться на обновление rus_verbs:нанести{}, // нанести на кожу rus_verbs:нарываться{}, // нарываться на неприятности rus_verbs:выводить{}, // выводить на орбиту rus_verbs:вернуться{}, // вернуться на родину rus_verbs:возвращаться{}, // возвращаться на родину прилагательное:падкий{}, // Он падок на деньги. прилагательное:обиженный{}, // Он обижен на отца. rus_verbs:косить{}, // Он косит на оба глаза. rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок. прилагательное:готовый{}, // Он готов на всякие жертвы. rus_verbs:говорить{}, // Он говорит на скользкую тему. прилагательное:глухой{}, // Он глух на одно ухо. rus_verbs:взять{}, // Он взял ребёнка себе на колени. rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия. rus_verbs:вести{}, // Лестница ведёт на третий этаж. rus_verbs:уполномочивать{}, // уполномочивать на что-либо глагол:спешить{ вид:несоверш }, // Я спешу на поезд. rus_verbs:брать{}, // Я беру всю ответственность на себя. rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление. rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики. rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку. rus_verbs:разбираться{}, // Эта машина разбирается на части. rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние. rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп. rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье. rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно. rus_verbs:делиться{}, // Тридцать делится на пять без остатка. rus_verbs:удаляться{}, // Суд удаляется на совещание. rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север. rus_verbs:сохранить{}, // Сохраните это на память обо мне. rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию. rus_verbs:лететь{}, // Самолёт летит на север. rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров. // rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи. rus_verbs:смотреть{}, // Она смотрит на нас из окна. rus_verbs:отдать{}, // Она отдала мне деньги на сохранение. rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину. rus_verbs:любоваться{}, // гости любовались на картину rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь. прилагательное:действительный{}, // Прививка оспы действительна только на три года. rus_verbs:спуститься{}, // На город спустился смог прилагательное:нечистый{}, // Он нечист на руку. прилагательное:неспособный{}, // Он неспособен на такую низость. прилагательное:злой{}, // кот очень зол на хозяина rus_verbs:пойти{}, // Девочка не пошла на урок физультуры rus_verbs:прибывать{}, // мой поезд прибывает на первый путь rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу rus_verbs:идти{}, // Дело идёт на лад. rus_verbs:лазить{}, // Он лазил на чердак. rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры. // rus_verbs:действовать{}, // действующий на нервы rus_verbs:выходить{}, // Балкон выходит на площадь. rus_verbs:работать{}, // Время работает на нас. глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина. rus_verbs:бросить{}, // Они бросили все силы на строительство. // глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков. rus_verbs:броситься{}, // Она радостно бросилась мне на шею. rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью. rus_verbs:ответить{}, // Она не ответила на мой поклон. rus_verbs:нашивать{}, // Она нашивала заплату на локоть. rus_verbs:молиться{}, // Она молится на свою мать. rus_verbs:запереть{}, // Она заперла дверь на замок. rus_verbs:заявить{}, // Она заявила свои права на наследство. rus_verbs:уйти{}, // Все деньги ушли на путешествие. rus_verbs:вступить{}, // Водолаз вступил на берег. rus_verbs:сойти{}, // Ночь сошла на землю. rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано. rus_verbs:рыдать{}, // Не рыдай так безумно над ним. rus_verbs:подписать{}, // Не забудьте подписать меня на газету. rus_verbs:держать{}, // Наш пароход держал курс прямо на север. rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира. rus_verbs:ехать{}, // Мы сейчас едем на завод. rus_verbs:выбросить{}, // Волнами лодку выбросило на берег. ГЛ_ИНФ(сесть), // сесть на снег ГЛ_ИНФ(записаться), ГЛ_ИНФ(положить) // положи книгу на стол } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: залить на youtube fact гл_предл { if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} } then return true } fact гл_предл { if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } } then return true } // смещаться на несколько миллиметров fact гл_предл { if context { Гл_НА_Вин предлог:на{} наречие:*{} } then return true } // партия взяла на себя нереалистичные обязательства fact гл_предл { if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} } then return true } #endregion ВИНИТЕЛЬНЫЙ // Все остальные варианты с предлогом 'НА' по умолчанию запрещаем. fact гл_предл { if context { * предлог:на{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:вин } } then return false,-4 } // Этот вариант нужен для обработки конструкций с числительными: // Президентские выборы разделили Венесуэлу на два непримиримых лагеря fact гл_предл { if context { * предлог:на{} *:*{ падеж:род } } then return false,-4 } // Продавать на eBay fact гл_предл { if context { * предлог:на{} * } then return false,-6 } #endregion Предлог_НА #region Предлог_С // ------------- ПРЕДЛОГ 'С' ----------------- // У этого предлога предпочтительная семантика привязывает его обычно к существительному. // Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим. #region ТВОРИТЕЛЬНЫЙ wordentry_set Гл_С_Твор={ rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться rus_verbs:забраться{}, rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ) rus_verbs:БИТЬСЯ{}, // rus_verbs:ПОДРАТЬСЯ{}, // прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ) rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ) rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ) rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ) rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ) прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом. rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ) rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ) rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ) rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ) rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ) rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ) rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ) rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ) rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ) rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ) rus_verbs:отправить{}, // вы можете отправить со мной человека rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор) rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С) rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С) прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С) rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С) rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С) rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С) rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С) rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С) rus_verbs:СВЫКАТЬСЯ{}, rus_verbs:стаскиваться{}, rus_verbs:спиливаться{}, rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С) rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор) rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С) rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С) rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С) rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С) rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С) rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С) rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С) rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С) rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С) rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор) rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С) rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С) rus_verbs:согласиться{}, // с этим согласились все (согласиться с) rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор) rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С) rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С) rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор) rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор) rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С) rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С) rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор) rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор) rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор) rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор) rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор) rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор) rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор) rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор) rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор) rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ) rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ) rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много) rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С) rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С) rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С) rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С) rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С) rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор) rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С) rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С) rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С) rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С) rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С) инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара. инфинитив:кристаллизоваться{ вид:несоверш }, глагол:кристаллизоваться{ вид:соверш }, глагол:кристаллизоваться{ вид:несоверш }, rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С) rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С) rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С) rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С) rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С) rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор) rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С) rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С) rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с) rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с) rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с) rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с) rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело. rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором rus_verbs:стирать{}, // стирать с мылом рубашку в тазу rus_verbs:прыгать{}, // парашютист прыгает с парашютом rus_verbs:выступить{}, // Он выступил с приветствием съезду. rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят. rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой. rus_verbs:вставать{}, // он встаёт с зарёй rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером. rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью. rus_verbs:договориться{}, // мы договоримся с вами rus_verbs:побыть{}, // он хотел побыть с тобой rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью rus_verbs:вязаться{}, // вязаться с фактами rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:относиться{}, // относиться с пониманием rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов. rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней rus_verbs:гулять{}, // бабушка гуляет с внуком rus_verbs:разбираться{}, // разбираться с задачей rus_verbs:сверить{}, // Данные были сверены с эталонными значениями rus_verbs:делать{}, // Что делать со старым телефоном rus_verbs:осматривать{}, // осматривать с удивлением rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре rus_verbs:попрощаться{}, // попрощаться с талантливым актером rus_verbs:задремать{}, // задремать с кружкой чая в руке rus_verbs:связать{}, // связать катастрофу с действиями конкурентов rus_verbs:носиться{}, // носиться с безумной идеей rus_verbs:кончать{}, // кончать с собой rus_verbs:обмениваться{}, // обмениваться с собеседниками rus_verbs:переговариваться{}, // переговариваться с маяком rus_verbs:общаться{}, // общаться с полицией rus_verbs:завершить{}, // завершить с ошибкой rus_verbs:обняться{}, // обняться с подругой rus_verbs:сливаться{}, // сливаться с фоном rus_verbs:смешаться{}, // смешаться с толпой rus_verbs:договариваться{}, // договариваться с потерпевшим rus_verbs:обедать{}, // обедать с гостями rus_verbs:сообщаться{}, // сообщаться с подземной рекой rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц rus_verbs:читаться{}, // читаться с трудом rus_verbs:смириться{}, // смириться с утратой rus_verbs:разделить{}, // разделить с другими ответственность rus_verbs:роднить{}, // роднить с медведем rus_verbs:медлить{}, // медлить с ответом rus_verbs:скрестить{}, // скрестить с ужом rus_verbs:покоиться{}, // покоиться с миром rus_verbs:делиться{}, // делиться с друзьями rus_verbs:познакомить{}, // познакомить с Олей rus_verbs:порвать{}, // порвать с Олей rus_verbs:завязать{}, // завязать с Олей знакомство rus_verbs:суетиться{}, // суетиться с изданием романа rus_verbs:соединиться{}, // соединиться с сервером rus_verbs:справляться{}, // справляться с нуждой rus_verbs:замешкаться{}, // замешкаться с ответом rus_verbs:поссориться{}, // поссориться с подругой rus_verbs:ссориться{}, // ссориться с друзьями rus_verbs:торопить{}, // торопить с решением rus_verbs:поздравить{}, // поздравить с победой rus_verbs:проститься{}, // проститься с человеком rus_verbs:поработать{}, // поработать с деревом rus_verbs:приключиться{}, // приключиться с Колей rus_verbs:сговориться{}, // сговориться с Ваней rus_verbs:отъехать{}, // отъехать с ревом rus_verbs:объединять{}, // объединять с другой кампанией rus_verbs:употребить{}, // употребить с молоком rus_verbs:перепутать{}, // перепутать с другой книгой rus_verbs:запоздать{}, // запоздать с ответом rus_verbs:подружиться{}, // подружиться с другими детьми rus_verbs:дружить{}, // дружить с Сережей rus_verbs:поравняться{}, // поравняться с финишной чертой rus_verbs:ужинать{}, // ужинать с гостями rus_verbs:расставаться{}, // расставаться с приятелями rus_verbs:завтракать{}, // завтракать с семьей rus_verbs:объединиться{}, // объединиться с соседями rus_verbs:сменяться{}, // сменяться с напарником rus_verbs:соединить{}, // соединить с сетью rus_verbs:разговориться{}, // разговориться с охранником rus_verbs:преподнести{}, // преподнести с помпой rus_verbs:напечатать{}, // напечатать с картинками rus_verbs:соединять{}, // соединять с сетью rus_verbs:расправиться{}, // расправиться с беззащитным человеком rus_verbs:распрощаться{}, // распрощаться с деньгами rus_verbs:сравнить{}, // сравнить с конкурентами rus_verbs:ознакомиться{}, // ознакомиться с выступлением инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{}, rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия rus_verbs:прощаться{}, // прощаться с боевым товарищем rus_verbs:сравнивать{}, // сравнивать с конкурентами rus_verbs:складывать{}, // складывать с весом упаковки rus_verbs:повестись{}, // повестись с ворами rus_verbs:столкнуть{}, // столкнуть с отбойником rus_verbs:переглядываться{}, // переглядываться с соседом rus_verbs:поторопить{}, // поторопить с откликом rus_verbs:развлекаться{}, // развлекаться с подружками rus_verbs:заговаривать{}, // заговаривать с незнакомцами rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим деепричастие:согласуясь{}, прилагательное:согласующийся{}, rus_verbs:совпасть{}, // совпасть с оригиналом rus_verbs:соединяться{}, // соединяться с куратором rus_verbs:повстречаться{}, // повстречаться с героями rus_verbs:поужинать{}, // поужинать с родителями rus_verbs:развестись{}, // развестись с первым мужем rus_verbs:переговорить{}, // переговорить с коллегами rus_verbs:сцепиться{}, // сцепиться с бродячей собакой rus_verbs:сожрать{}, // сожрать с потрохами rus_verbs:побеседовать{}, // побеседовать со шпаной rus_verbs:поиграть{}, // поиграть с котятами rus_verbs:сцепить{}, // сцепить с тягачом rus_verbs:помириться{}, // помириться с подружкой rus_verbs:связываться{}, // связываться с бандитами rus_verbs:совещаться{}, // совещаться с мастерами rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой rus_verbs:переплестись{}, // переплестись с кустами rus_verbs:мутить{}, // мутить с одногрупницами rus_verbs:приглядываться{}, // приглядываться с интересом rus_verbs:сблизиться{}, // сблизиться с врагами rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой rus_verbs:растереть{}, // растереть с солью rus_verbs:смешиваться{}, // смешиваться с известью rus_verbs:соприкоснуться{}, // соприкоснуться с тайной rus_verbs:ладить{}, // ладить с родственниками rus_verbs:сотрудничать{}, // сотрудничать с органами дознания rus_verbs:съехаться{}, // съехаться с родственниками rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов rus_verbs:советоваться{}, // советоваться с отчимом rus_verbs:сравниться{}, // сравниться с лучшими rus_verbs:знакомиться{}, // знакомиться с абитуриентами rus_verbs:нырять{}, // нырять с аквалангом rus_verbs:забавляться{}, // забавляться с куклой rus_verbs:перекликаться{}, // перекликаться с другой статьей rus_verbs:тренироваться{}, // тренироваться с партнершей rus_verbs:поспорить{}, // поспорить с казночеем инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш }, rus_verbs:примириться{}, // примириться с утратой rus_verbs:раскланяться{}, // раскланяться с фрейлинами rus_verbs:слечь{}, // слечь с ангиной rus_verbs:соприкасаться{}, // соприкасаться со стеной rus_verbs:смешать{}, // смешать с грязью rus_verbs:пересекаться{}, // пересекаться с трассой rus_verbs:путать{}, // путать с государственной шерстью rus_verbs:поболтать{}, // поболтать с ученицами rus_verbs:здороваться{}, // здороваться с профессором rus_verbs:просчитаться{}, // просчитаться с покупкой rus_verbs:сторожить{}, // сторожить с собакой rus_verbs:обыскивать{}, // обыскивать с собаками rus_verbs:переплетаться{}, // переплетаться с другой веткой rus_verbs:обниматься{}, // обниматься с Ксюшей rus_verbs:объединяться{}, // объединяться с конкурентами rus_verbs:погорячиться{}, // погорячиться с покупкой rus_verbs:мыться{}, // мыться с мылом rus_verbs:свериться{}, // свериться с эталоном rus_verbs:разделаться{}, // разделаться с кем-то rus_verbs:чередоваться{}, // чередоваться с партнером rus_verbs:налететь{}, // налететь с соратниками rus_verbs:поспать{}, // поспать с включенным светом rus_verbs:управиться{}, // управиться с собакой rus_verbs:согрешить{}, // согрешить с замужней rus_verbs:определиться{}, // определиться с победителем rus_verbs:перемешаться{}, // перемешаться с гранулами rus_verbs:затрудняться{}, // затрудняться с ответом rus_verbs:обождать{}, // обождать со стартом rus_verbs:фыркать{}, // фыркать с презрением rus_verbs:засидеться{}, // засидеться с приятелем rus_verbs:крепнуть{}, // крепнуть с годами rus_verbs:пировать{}, // пировать с дружиной rus_verbs:щебетать{}, // щебетать с сестричками rus_verbs:маяться{}, // маяться с кашлем rus_verbs:сближать{}, // сближать с центральным светилом rus_verbs:меркнуть{}, // меркнуть с возрастом rus_verbs:заспорить{}, // заспорить с оппонентами rus_verbs:граничить{}, // граничить с Ливаном rus_verbs:перестараться{}, // перестараться со стимуляторами rus_verbs:объединить{}, // объединить с филиалом rus_verbs:свыкнуться{}, // свыкнуться с утратой rus_verbs:посоветоваться{}, // посоветоваться с адвокатами rus_verbs:напутать{}, // напутать с ведомостями rus_verbs:нагрянуть{}, // нагрянуть с обыском rus_verbs:посовещаться{}, // посовещаться с судьей rus_verbs:провернуть{}, // провернуть с друганом rus_verbs:разделяться{}, // разделяться с сотрапезниками rus_verbs:пересечься{}, // пересечься с второй колонной rus_verbs:опережать{}, // опережать с большим запасом rus_verbs:перепутаться{}, // перепутаться с другой линией rus_verbs:соотноситься{}, // соотноситься с затратами rus_verbs:смешивать{}, // смешивать с золой rus_verbs:свидеться{}, // свидеться с тобой rus_verbs:переспать{}, // переспать с графиней rus_verbs:поладить{}, // поладить с соседями rus_verbs:протащить{}, // протащить с собой rus_verbs:разминуться{}, // разминуться с встречным потоком rus_verbs:перемежаться{}, // перемежаться с успехами rus_verbs:рассчитаться{}, // рассчитаться с кредиторами rus_verbs:срастись{}, // срастись с телом rus_verbs:знакомить{}, // знакомить с родителями rus_verbs:поругаться{}, // поругаться с родителями rus_verbs:совладать{}, // совладать с чувствами rus_verbs:обручить{}, // обручить с богатой невестой rus_verbs:сближаться{}, // сближаться с вражеским эсминцем rus_verbs:замутить{}, // замутить с Ксюшей rus_verbs:повозиться{}, // повозиться с настройкой rus_verbs:торговаться{}, // торговаться с продавцами rus_verbs:уединиться{}, // уединиться с девчонкой rus_verbs:переборщить{}, // переборщить с добавкой rus_verbs:ознакомить{}, // ознакомить с пожеланиями rus_verbs:прочесывать{}, // прочесывать с собаками rus_verbs:переписываться{}, // переписываться с корреспондентами rus_verbs:повздорить{}, // повздорить с сержантом rus_verbs:разлучить{}, // разлучить с семьей rus_verbs:соседствовать{}, // соседствовать с цыганами rus_verbs:застукать{}, // застукать с проститутками rus_verbs:напуститься{}, // напуститься с кулаками rus_verbs:сдружиться{}, // сдружиться с ребятами rus_verbs:соперничать{}, // соперничать с параллельным классом rus_verbs:прочесать{}, // прочесать с собаками rus_verbs:кокетничать{}, // кокетничать с гимназистками rus_verbs:мириться{}, // мириться с убытками rus_verbs:оплошать{}, // оплошать с билетами rus_verbs:отождествлять{}, // отождествлять с литературным героем rus_verbs:хитрить{}, // хитрить с зарплатой rus_verbs:провозиться{}, // провозиться с задачкой rus_verbs:коротать{}, // коротать с друзьями rus_verbs:соревноваться{}, // соревноваться с машиной rus_verbs:уживаться{}, // уживаться с местными жителями rus_verbs:отождествляться{}, // отождествляться с литературным героем rus_verbs:сопоставить{}, // сопоставить с эталоном rus_verbs:пьянствовать{}, // пьянствовать с друзьями rus_verbs:залетать{}, // залетать с паленой водкой rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой rus_verbs:запаздывать{}, // запаздывать с кормлением rus_verbs:таскаться{}, // таскаться с сумками rus_verbs:контрастировать{}, // контрастировать с туфлями rus_verbs:сшибиться{}, // сшибиться с форвардом rus_verbs:состязаться{}, // состязаться с лучшей командой rus_verbs:затрудниться{}, // затрудниться с объяснением rus_verbs:объясниться{}, // объясниться с пострадавшими rus_verbs:разводиться{}, // разводиться со сварливой женой rus_verbs:препираться{}, // препираться с адвокатами rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками rus_verbs:свестись{}, // свестись с нулевым счетом rus_verbs:обговорить{}, // обговорить с директором rus_verbs:обвенчаться{}, // обвенчаться с ведьмой rus_verbs:экспериментировать{}, // экспериментировать с генами rus_verbs:сверять{}, // сверять с таблицей rus_verbs:сверяться{}, // свериться с таблицей rus_verbs:сблизить{}, // сблизить с точкой rus_verbs:гармонировать{}, // гармонировать с обоями rus_verbs:перемешивать{}, // перемешивать с молоком rus_verbs:трепаться{}, // трепаться с сослуживцами rus_verbs:перемигиваться{}, // перемигиваться с соседкой rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем rus_verbs:распить{}, // распить с собутыльниками rus_verbs:скрестись{}, // скрестись с дикой лошадью rus_verbs:передраться{}, // передраться с дворовыми собаками rus_verbs:умыть{}, // умыть с мылом rus_verbs:грызться{}, // грызться с соседями rus_verbs:переругиваться{}, // переругиваться с соседями rus_verbs:доиграться{}, // доиграться со спичками rus_verbs:заладиться{}, // заладиться с подругой rus_verbs:скрещиваться{}, // скрещиваться с дикими видами rus_verbs:повидаться{}, // повидаться с дедушкой rus_verbs:повоевать{}, // повоевать с орками rus_verbs:сразиться{}, // сразиться с лучшим рыцарем rus_verbs:кипятить{}, // кипятить с отбеливателем rus_verbs:усердствовать{}, // усердствовать с наказанием rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером rus_verbs:пошептаться{}, // пошептаться с судьями rus_verbs:сравняться{}, // сравняться с лучшими экземплярами rus_verbs:церемониться{}, // церемониться с пьяницами rus_verbs:консультироваться{}, // консультироваться со специалистами rus_verbs:переусердствовать{}, // переусердствовать с наказанием rus_verbs:проноситься{}, // проноситься с собой rus_verbs:перемешать{}, // перемешать с гипсом rus_verbs:темнить{}, // темнить с долгами rus_verbs:сталкивать{}, // сталкивать с черной дырой rus_verbs:увольнять{}, // увольнять с волчьим билетом rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт rus_verbs:созвониться{}, // созвониться с мамой rus_verbs:спеться{}, // спеться с отъявленными хулиганами rus_verbs:интриговать{}, // интриговать с придворными rus_verbs:приобрести{}, // приобрести со скидкой rus_verbs:задержаться{}, // задержаться со сдачей работы rus_verbs:плавать{}, // плавать со спасательным кругом rus_verbs:якшаться{}, // Не якшайся с врагами инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги инфинитив:ассоциировать{вид:несоверш}, глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги глагол:ассоциировать{вид:несоверш}, //+прилагательное:ассоциировавший{вид:несоверш}, прилагательное:ассоциировавший{вид:соверш}, прилагательное:ассоциирующий{}, деепричастие:ассоциируя{}, деепричастие:ассоциировав{}, rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов //+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом //+глагол:аффилировать{вид:соверш}, прилагательное:аффилированный{}, rus_verbs:баловаться{}, // мальчик баловался с молотком rus_verbs:балясничать{}, // женщина балясничала с товарками rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями rus_verbs:бодаться{}, // теленок бодается с деревом rus_verbs:боксировать{}, // Майкл дважды боксировал с ним rus_verbs:брататься{}, // Солдаты братались с бойцами союзников rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:происходить{}, // Что происходит с мировой экономикой? rus_verbs:произойти{}, // Что произошло с экономикой? rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:водиться{}, // Няня водится с детьми rus_verbs:воевать{}, // Фермеры воевали с волками rus_verbs:возиться{}, // Няня возится с детьми rus_verbs:ворковать{}, // Голубь воркует с голубкой rus_verbs:воссоединиться{}, // Дети воссоединились с семьей rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой rus_verbs:враждовать{}, // враждовать с соседями rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:расстаться{}, // я не могу расстаться с тобой rus_verbs:выдирать{}, // выдирать с мясом rus_verbs:выдираться{}, // выдираться с мясом rus_verbs:вытворить{}, // вытворить что-либо с чем-либо rus_verbs:вытворять{}, // вытворять что-либо с чем-либо rus_verbs:сделать{}, // сделать с чем-то rus_verbs:домыть{}, // домыть с мылом rus_verbs:случиться{}, // случиться с кем-то rus_verbs:остаться{}, // остаться с кем-то rus_verbs:случать{}, // случать с породистым кобельком rus_verbs:послать{}, // послать с весточкой rus_verbs:работать{}, // работать с роботами rus_verbs:провести{}, // провести с девчонками время rus_verbs:заговорить{}, // заговорить с незнакомкой rus_verbs:прошептать{}, // прошептать с придыханием rus_verbs:читать{}, // читать с выражением rus_verbs:слушать{}, // слушать с повышенным вниманием rus_verbs:принести{}, // принести с собой rus_verbs:спать{}, // спать с женщинами rus_verbs:закончить{}, // закончить с приготовлениями rus_verbs:помочь{}, // помочь с перестановкой rus_verbs:уехать{}, // уехать с семьей rus_verbs:случаться{}, // случаться с кем-то rus_verbs:кутить{}, // кутить с проститутками rus_verbs:разговаривать{}, // разговаривать с ребенком rus_verbs:погодить{}, // погодить с ликвидацией rus_verbs:считаться{}, // считаться с чужим мнением rus_verbs:носить{}, // носить с собой rus_verbs:хорошеть{}, // хорошеть с каждым днем rus_verbs:приводить{}, // приводить с собой rus_verbs:прыгнуть{}, // прыгнуть с парашютом rus_verbs:петь{}, // петь с чувством rus_verbs:сложить{}, // сложить с результатом rus_verbs:познакомиться{}, // познакомиться с другими студентами rus_verbs:обращаться{}, // обращаться с животными rus_verbs:съесть{}, // съесть с хлебом rus_verbs:ошибаться{}, // ошибаться с дозировкой rus_verbs:столкнуться{}, // столкнуться с медведем rus_verbs:справиться{}, // справиться с нуждой rus_verbs:торопиться{}, // торопиться с ответом rus_verbs:поздравлять{}, // поздравлять с победой rus_verbs:объясняться{}, // объясняться с начальством rus_verbs:пошутить{}, // пошутить с подругой rus_verbs:поздороваться{}, // поздороваться с коллегами rus_verbs:поступать{}, // Как поступать с таким поведением? rus_verbs:определяться{}, // определяться с кандидатами rus_verbs:связаться{}, // связаться с поставщиком rus_verbs:спорить{}, // спорить с собеседником rus_verbs:разобраться{}, // разобраться с делами rus_verbs:ловить{}, // ловить с удочкой rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос rus_verbs:шутить{}, // шутить с диким зверем rus_verbs:разорвать{}, // разорвать с поставщиком контракт rus_verbs:увезти{}, // увезти с собой rus_verbs:унести{}, // унести с собой rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее rus_verbs:складываться{}, // складываться с первым импульсом rus_verbs:соглашаться{}, // соглашаться с предложенным договором //rus_verbs:покончить{}, // покончить с развратом rus_verbs:прихватить{}, // прихватить с собой rus_verbs:похоронить{}, // похоронить с почестями rus_verbs:связывать{}, // связывать с компанией свою судьбу rus_verbs:совпадать{}, // совпадать с предсказанием rus_verbs:танцевать{}, // танцевать с девушками rus_verbs:поделиться{}, // поделиться с выжившими rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате. rus_verbs:беседовать{}, // преподаватель, беседующий со студентами rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками rus_verbs:поговорить{}, // поговорить с виновниками rus_verbs:сказать{}, // сказать с трудом rus_verbs:произнести{}, // произнести с трудом rus_verbs:говорить{}, // говорить с акцентом rus_verbs:произносить{}, // произносить с трудом rus_verbs:встречаться{}, // кто с Антонио встречался? rus_verbs:посидеть{}, // посидеть с друзьями rus_verbs:расквитаться{}, // расквитаться с обидчиком rus_verbs:поквитаться{}, // поквитаться с обидчиком rus_verbs:ругаться{}, // ругаться с женой rus_verbs:поскандалить{}, // поскандалить с женой rus_verbs:потанцевать{}, // потанцевать с подругой rus_verbs:скандалить{}, // скандалить с соседями rus_verbs:разругаться{}, // разругаться с другом rus_verbs:болтать{}, // болтать с подругами rus_verbs:потрепаться{}, // потрепаться с соседкой rus_verbs:войти{}, // войти с регистрацией rus_verbs:входить{}, // входить с регистрацией rus_verbs:возвращаться{}, // возвращаться с триумфом rus_verbs:опоздать{}, // Он опоздал с подачей сочинения. rus_verbs:молчать{}, // Он молчал с ледяным спокойствием. rus_verbs:сражаться{}, // Он героически сражался с врагами. rus_verbs:выходить{}, // Он всегда выходит с зонтиком. rus_verbs:сличать{}, // сличать перевод с оригиналом rus_verbs:начать{}, // я начал с товарищем спор о религии rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки rus_verbs:приходить{}, // Приходите с нею. rus_verbs:жить{}, // кто с тобой жил? rus_verbs:расходиться{}, // Маша расходится с Петей rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой rus_verbs:торговать{}, // мы торгуем с ними нефтью rus_verbs:уединяться{}, // уединяться с подругой в доме rus_verbs:уладить{}, // уладить конфликт с соседями rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем. rus_verbs:разделять{}, // Я разделяю с вами горе и радость. rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи. rus_verbs:захватить{}, // Я не захватил с собой денег. прилагательное:знакомый{}, // Я знаком с ними обоими. rus_verbs:вести{}, // Я веду с ней переписку. прилагательное:сопряженный{}, // Это сопряжено с большими трудностями. прилагательное:связанный{причастие}, // Это дело связано с риском. rus_verbs:поехать{}, // Хотите поехать со мной в театр? rus_verbs:проснуться{}, // Утром я проснулся с ясной головой. rus_verbs:лететь{}, // Самолёт летел со скоростью звука. rus_verbs:играть{}, // С огнём играть опасно! rus_verbs:поделать{}, // С ним ничего не поделаешь. rus_verbs:стрястись{}, // С ней стряслось несчастье. rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием. rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием. rus_verbs:разойтись{}, // Она разошлась с мужем. rus_verbs:пристать{}, // Она пристала ко мне с расспросами. rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением. rus_verbs:поступить{}, // Она плохо поступила с ним. rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом. rus_verbs:взять{}, // Возьмите с собой только самое необходимое. rus_verbs:наплакаться{}, // Наплачется она с ним. rus_verbs:лежать{}, // Он лежит с воспалением лёгких. rus_verbs:дышать{}, // дышащий с трудом rus_verbs:брать{}, // брать с собой rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой. rus_verbs:упасть{}, // Ваза упала со звоном. rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком rus_verbs:сидеть{}, // Она сидит дома с ребенком rus_verbs:встретиться{}, // встречаться с кем-либо ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{}, rus_verbs:мыть{} } fact гл_предл { if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} } then return true } #endregion ТВОРИТЕЛЬНЫЙ #region РОДИТЕЛЬНЫЙ wordentry_set Гл_С_Род= { rus_verbs:УХОДИТЬ{}, // Но с базы не уходить. rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ) rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ) rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ) rus_verbs:РАЗГЛЯДЕТЬ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ) rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ) rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ) rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ) rus_verbs:ЗАРЕВЕТЬ{}, // rus_verbs:ПРОРЕВЕТЬ{}, // rus_verbs:ЗАОРАТЬ{}, // rus_verbs:ПРООРАТЬ{}, // rus_verbs:ОРАТЬ{}, // rus_verbs:ЗАКРИЧАТЬ{}, rus_verbs:ВОПИТЬ{}, // rus_verbs:ЗАВОПИТЬ{}, // rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ) rus_verbs:СТАСКИВАТЬ{}, // rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ) rus_verbs:ЗАВЫТЬ{}, // rus_verbs:ВЫТЬ{}, // rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ) rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:собирать{}, // мальчики начали собирать со столов посуду rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ) rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ) rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ) rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ) rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ) rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род) rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род) rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С) rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С) rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род) rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С) rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С) rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С) rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С) rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род) rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род) rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род) rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род) rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род) rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С) rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род) rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род) rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род) rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род) rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род) rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род) rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С) rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род) rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род) rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род) rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С) rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С) rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С) прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С) rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С) rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род) rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С) rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с) rus_verbs:спасть{}, // тяжесть спала с души. (спасть с) rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С) rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С) rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С) rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то) rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С) rus_verbs:приближаться{}, // со стороны острова приближалась лодка. rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С) rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с) rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с) rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С) rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С) rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С) rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С) rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С) rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С) rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.) rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С) rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С) rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С) rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С) rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с) rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С) rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с) rus_verbs:вставать{}, // Он не встает с кровати. (вставать с) rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с) rus_verbs:причитаться{}, // С вас причитается 50 рублей. rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки. rus_verbs:сократить{}, // Его сократили со службы. rus_verbs:поднять{}, // рука подняла с пола rus_verbs:поднимать{}, rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни. rus_verbs:полететь{}, // Мальчик полетел с лестницы. rus_verbs:литься{}, // вода льется с неба rus_verbs:натечь{}, // натечь с сапог rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая rus_verbs:съезжать{}, // съезжать с заявленной темы rus_verbs:покатываться{}, // покатываться со смеху rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:сдирать{}, // сдирать с тела кожу rus_verbs:соскальзывать{}, // соскальзывать с крючка rus_verbs:сметать{}, // сметать с прилавков rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки rus_verbs:прокаркать{}, // прокаркать с ветки rus_verbs:стряхивать{}, // стряхивать с одежды rus_verbs:сваливаться{}, // сваливаться с лестницы rus_verbs:слизнуть{}, // слизнуть с лица rus_verbs:доставляться{}, // доставляться с фермы rus_verbs:обступать{}, // обступать с двух сторон rus_verbs:повскакивать{}, // повскакивать с мест rus_verbs:обозревать{}, // обозревать с вершины rus_verbs:слинять{}, // слинять с урока rus_verbs:смывать{}, // смывать с лица rus_verbs:спихнуть{}, // спихнуть со стола rus_verbs:обозреть{}, // обозреть с вершины rus_verbs:накупить{}, // накупить с рук rus_verbs:схлынуть{}, // схлынуть с берега rus_verbs:спикировать{}, // спикировать с километровой высоты rus_verbs:уползти{}, // уползти с поля боя rus_verbs:сбиваться{}, // сбиваться с пути rus_verbs:отлучиться{}, // отлучиться с поста rus_verbs:сигануть{}, // сигануть с крыши rus_verbs:сместить{}, // сместить с поста rus_verbs:списать{}, // списать с оригинального устройства инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы деепричастие:слетая{}, rus_verbs:напиваться{}, // напиваться с горя rus_verbs:свесить{}, // свесить с крыши rus_verbs:заполучить{}, // заполучить со склада rus_verbs:спадать{}, // спадать с глаз rus_verbs:стартовать{}, // стартовать с мыса rus_verbs:спереть{}, // спереть со склада rus_verbs:согнать{}, // согнать с живота rus_verbs:скатываться{}, // скатываться со стога rus_verbs:сняться{}, // сняться с выборов rus_verbs:слезать{}, // слезать со стола rus_verbs:деваться{}, // деваться с подводной лодки rus_verbs:огласить{}, // огласить с трибуны rus_verbs:красть{}, // красть со склада rus_verbs:расширить{}, // расширить с торца rus_verbs:угадывать{}, // угадывать с полуслова rus_verbs:оскорбить{}, // оскорбить со сцены rus_verbs:срывать{}, // срывать с головы rus_verbs:сшибить{}, // сшибить с коня rus_verbs:сбивать{}, // сбивать с одежды rus_verbs:содрать{}, // содрать с посетителей rus_verbs:столкнуть{}, // столкнуть с горы rus_verbs:отряхнуть{}, // отряхнуть с одежды rus_verbs:сбрасывать{}, // сбрасывать с борта rus_verbs:расстреливать{}, // расстреливать с борта вертолета rus_verbs:придти{}, // мать скоро придет с работы rus_verbs:съехать{}, // Миша съехал с горки rus_verbs:свисать{}, // свисать с веток rus_verbs:стянуть{}, // стянуть с кровати rus_verbs:скинуть{}, // скинуть снег с плеча rus_verbs:загреметь{}, // загреметь со стула rus_verbs:сыпаться{}, // сыпаться с неба rus_verbs:стряхнуть{}, // стряхнуть с головы rus_verbs:сползти{}, // сползти со стула rus_verbs:стереть{}, // стереть с экрана rus_verbs:прогнать{}, // прогнать с фермы rus_verbs:смахнуть{}, // смахнуть со стола rus_verbs:спускать{}, // спускать с поводка rus_verbs:деться{}, // деться с подводной лодки rus_verbs:сдернуть{}, // сдернуть с себя rus_verbs:сдвинуться{}, // сдвинуться с места rus_verbs:слететь{}, // слететь с катушек rus_verbs:обступить{}, // обступить со всех сторон rus_verbs:снести{}, // снести с плеч инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков деепричастие:сбегая{}, прилагательное:сбегающий{}, // прилагательное:сбегавший{ вид:несоверш }, rus_verbs:запить{}, // запить с горя rus_verbs:рубануть{}, // рубануть с плеча rus_verbs:чертыхнуться{}, // чертыхнуться с досады rus_verbs:срываться{}, // срываться с цепи rus_verbs:смыться{}, // смыться с уроков rus_verbs:похитить{}, // похитить со склада rus_verbs:смести{}, // смести со своего пути rus_verbs:отгружать{}, // отгружать со склада rus_verbs:отгрузить{}, // отгрузить со склада rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя rus_verbs:взиматься{}, // Плата взимается с любого посетителя rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков rus_verbs:вспархивать{}, // вспархивать с цветка rus_verbs:вспорхнуть{}, // вспорхнуть с ветки rus_verbs:выбросить{}, // выбросить что-то с балкона rus_verbs:выводить{}, // выводить с одежды пятна rus_verbs:снять{}, // снять с головы rus_verbs:начинать{}, // начинать с эскиза rus_verbs:двинуться{}, // двинуться с места rus_verbs:начинаться{}, // начинаться с гардероба rus_verbs:стечь{}, // стечь с крыши rus_verbs:слезть{}, // слезть с кучи rus_verbs:спуститься{}, // спуститься с крыши rus_verbs:сойти{}, // сойти с пьедестала rus_verbs:свернуть{}, // свернуть с пути rus_verbs:сорвать{}, // сорвать с цепи rus_verbs:сорваться{}, // сорваться с поводка rus_verbs:тронуться{}, // тронуться с места rus_verbs:угадать{}, // угадать с первой попытки rus_verbs:спустить{}, // спустить с лестницы rus_verbs:соскочить{}, // соскочить с крючка rus_verbs:сдвинуть{}, // сдвинуть с места rus_verbs:подниматься{}, // туман, поднимающийся с болота rus_verbs:подняться{}, // туман, поднявшийся с болота rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног. rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног. rus_verbs:донестись{}, // С улицы донесся шум дождя. rus_verbs:опасть{}, // Опавшие с дерева листья. rus_verbs:махнуть{}, // Он махнул с берега в воду. rus_verbs:исчезнуть{}, // исчезнуть с экрана rus_verbs:свалиться{}, // свалиться со сцены rus_verbs:упасть{}, // упасть с дерева rus_verbs:вернуться{}, // Он ещё не вернулся с работы. rus_verbs:сдувать{}, // сдувать пух с одуванчиков rus_verbs:свергать{}, // свергать царя с трона rus_verbs:сбиться{}, // сбиться с пути rus_verbs:стирать{}, // стирать тряпкой надпись с доски rus_verbs:убирать{}, // убирать мусор c пола rus_verbs:удалять{}, // удалять игрока с поля rus_verbs:окружить{}, // Япония окружена со всех сторон морями. rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение. глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы. прилагательное:спокойный{}, // С этой стороны я спокоен. rus_verbs:спросить{}, // С тебя за всё спросят. rus_verbs:течь{}, // С него течёт пот. rus_verbs:дуть{}, // С моря дует ветер. rus_verbs:капать{}, // С его лица капали крупные капли пота. rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол. rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня. rus_verbs:встать{}, // Все встали со стульев. rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто. rus_verbs:взять{}, // Возьми книгу с полки. rus_verbs:спускаться{}, // Мы спускались с горы. rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы. rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок. rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы. rus_verbs:двигаться{}, // Он не двигался с места. rus_verbs:отходить{}, // мой поезд отходит с первого пути rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции rus_verbs:падать{}, // снег падает с ветвей rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия. } fact гл_предл { if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:род} } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:парт} } then return true } #endregion РОДИТЕЛЬНЫЙ fact гл_предл { if context { * предлог:с{} *:*{ падеж:твор } } then return false,-3 } fact гл_предл { if context { * предлог:с{} *:*{ падеж:род } } then return false,-4 } fact гл_предл { if context { * предлог:с{} * } then return false,-5 } #endregion Предлог_С /* #region Предлог_ПОД // -------------- ПРЕДЛОГ 'ПОД' ----------------------- fact гл_предл { if context { * предлог:под{} @regex("[a-z]+[0-9]*") } then return true } // ПОД+вин.п. не может присоединяться к существительным, поэтому // он присоединяется к любым глаголам. fact гл_предл { if context { * предлог:под{} *:*{ падеж:вин } } then return true } wordentry_set Гл_ПОД_твор= { rus_verbs:извиваться{}, // извивалась под его длинными усами rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ) rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ) rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ) rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ) rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ) rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ) rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть) rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ) rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ) rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ) rus_verbs:ПРОПОЛЗТИ{}, // rus_verbs:ПРОПОЛЗАТЬ{}, // rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ) rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ) rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ) rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ) rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ) rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом rus_verbs:иметься{}, // у каждого под рукой имелся арбалет rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ) rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ) rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ) rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ) rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ) rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ) rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ) rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ) rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ) rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ) rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ) rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ) rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ) rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор) rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ) rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ) rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ) rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ) rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ) rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ) rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ) rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ) rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ) rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ) rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ) rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ) rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ) rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ) rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ) rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ) rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ) rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ) rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ) rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ) rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ) rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД) rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ) rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД) rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ) rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ) rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ) rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ) rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ) rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ) rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ) rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ) rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ) rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ) rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ) rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ) rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ) rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ) rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ) rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ) rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ) rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ) rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ) rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ) rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ) rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ) rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ) rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ) rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ) rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ) rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ) rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ) rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ) rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ) rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД) rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД) rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД) rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД) rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД) rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД) rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД) rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД) rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор) rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД) rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД) rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД) rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД) rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД) rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД) rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД) rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД) rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД) rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД) rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД) rus_verbs:уснуть{}, // Миша уснет под одеялом rus_verbs:пошевелиться{}, // пошевелиться под одеялом rus_verbs:задохнуться{}, // задохнуться под слоем снега rus_verbs:потечь{}, // потечь под избыточным давлением rus_verbs:уцелеть{}, // уцелеть под завалами rus_verbs:мерцать{}, // мерцать под лучами софитов rus_verbs:поискать{}, // поискать под кроватью rus_verbs:гудеть{}, // гудеть под нагрузкой rus_verbs:посидеть{}, // посидеть под навесом rus_verbs:укрыться{}, // укрыться под навесом rus_verbs:утихнуть{}, // утихнуть под одеялом rus_verbs:заскрипеть{}, // заскрипеть под тяжестью rus_verbs:шелохнуться{}, // шелохнуться под одеялом инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш }, инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш }, деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш }, rus_verbs:пониматься{}, // пониматься под успехом rus_verbs:подразумеваться{}, // подразумеваться под правильным решением rus_verbs:промокнуть{}, // промокнуть под проливным дождем rus_verbs:засосать{}, // засосать под ложечкой rus_verbs:подписаться{}, // подписаться под воззванием rus_verbs:укрываться{}, // укрываться под навесом rus_verbs:запыхтеть{}, // запыхтеть под одеялом rus_verbs:мокнуть{}, // мокнуть под лождем rus_verbs:сгибаться{}, // сгибаться под тяжестью снега rus_verbs:намокнуть{}, // намокнуть под дождем rus_verbs:подписываться{}, // подписываться под обращением rus_verbs:тарахтеть{}, // тарахтеть под окнами инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача. деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{}, rus_verbs:лежать{}, // лежать под капельницей rus_verbs:вымокать{}, // вымокать под дождём rus_verbs:вымокнуть{}, // вымокнуть под дождём rus_verbs:проворчать{}, // проворчать под нос rus_verbs:хмыкнуть{}, // хмыкнуть под нос rus_verbs:отыскать{}, // отыскать под кроватью rus_verbs:дрогнуть{}, // дрогнуть под ударами rus_verbs:проявляться{}, // проявляться под нагрузкой rus_verbs:сдержать{}, // сдержать под контролем rus_verbs:ложиться{}, // ложиться под клиента rus_verbs:таять{}, // таять под весенним солнцем rus_verbs:покатиться{}, // покатиться под откос rus_verbs:лечь{}, // он лег под навесом rus_verbs:идти{}, // идти под дождем прилагательное:известный{}, // Он известен под этим именем. rus_verbs:стоять{}, // Ящик стоит под столом. rus_verbs:отступить{}, // Враг отступил под ударами наших войск. rus_verbs:царапаться{}, // Мышь царапается под полом. rus_verbs:спать{}, // заяц спокойно спал у себя под кустом rus_verbs:загорать{}, // мы загораем под солнцем ГЛ_ИНФ(мыть), // мыть руки под струёй воды ГЛ_ИНФ(закопать), ГЛ_ИНФ(спрятать), ГЛ_ИНФ(прятать), ГЛ_ИНФ(перепрятать) } fact гл_предл { if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } } then return true } // для глаголов вне списка - запрещаем. fact гл_предл { if context { * предлог:под{} *:*{ падеж:твор } } then return false,-10 } fact гл_предл { if context { * предлог:под{} *:*{} } then return false,-11 } #endregion Предлог_ПОД */ #region Предлог_ОБ // -------------- ПРЕДЛОГ 'ОБ' ----------------------- wordentry_set Гл_ОБ_предл= { rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ) rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ) rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ) rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом? rus_verbs:забывать{}, // Мы не можем забывать об их участи. rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ) rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ) rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ) rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ) rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ) rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ) rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ) rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ) rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ) rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ) rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об) rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об) rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ) rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ) rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ) rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе. rus_verbs:кричать{}, // Все газеты кричат об этом событии. rus_verbs:советоваться{}, // Она обо всём советуется с матерью. rus_verbs:говориться{}, // об остальном говорилось легко. rus_verbs:подумать{}, // нужно крепко обо всем подумать. rus_verbs:напомнить{}, // черный дым напомнил об опасности. rus_verbs:забыть{}, // забудь об этой роскоши. rus_verbs:думать{}, // приходится обо всем думать самой. rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:информировать{}, // информировать об изменениях rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:заговорить{}, // заговорить об оплате rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:попросить{}, // попросить об услуге rus_verbs:объявить{}, // объявить об отставке rus_verbs:предупредить{}, // предупредить об аварии rus_verbs:предупреждать{}, // предупреждать об опасности rus_verbs:твердить{}, // твердить об обязанностях rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:прочитать{}, // он читал об этом в учебнике rus_verbs:узнать{}, // он узнал об этом из фильмов rus_verbs:рассказать{}, // рассказать об экзаменах rus_verbs:рассказывать{}, rus_verbs:договориться{}, // договориться об оплате rus_verbs:договариваться{}, // договариваться об обмене rus_verbs:болтать{}, // Не болтай об этом! rus_verbs:проболтаться{}, // Не проболтайся об этом! rus_verbs:заботиться{}, // кто заботится об урегулировании rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне rus_verbs:помнить{}, // всем советую об этом помнить rus_verbs:мечтать{} // Мечтать об успехе } fact гл_предл { if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } } then return true } fact гл_предл { if context { * предлог:о{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { * предлог:об{} @regex("[a-z]+[0-9]*") } then return true } // остальные глаголы не могут связываться fact гл_предл { if context { * предлог:об{} *:*{ падеж:предл } } then return false, -4 } wordentry_set Гл_ОБ_вин= { rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ) rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ) rus_verbs:опереться{}, // Он опёрся об стену. rus_verbs:опираться{}, rus_verbs:постучать{}, // постучал лбом об пол. rus_verbs:удариться{}, // бутылка глухо ударилась об землю. rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:царапаться{} // Днище лодки царапалось обо что-то. } fact гл_предл { if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:об{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:об{} *:*{} } then return false,-5 } #endregion Предлог_ОБ #region Предлог_О // ------------------- С ПРЕДЛОГОМ 'О' ---------------------- wordentry_set Гл_О_Вин={ rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену. rus_verbs:болтать{}, // Болтали чаще всего о пустяках. rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг. rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол. rus_verbs:бахнуться{}, // Бахнуться головой о стол. rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ) rus_verbs:ВЫТИРАТЬ{}, // rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ) rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ) rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ) rus_verbs:ЛЯЗГАТЬ{}, // rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ) rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ) rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ) rus_verbs:колотиться{}, // сердце его колотилось о ребра rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей. rus_verbs:биться{}, // биться головой о стену? (биться о) rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о) rus_verbs:разбиваться{}, // волны разбивались о скалу rus_verbs:разбивать{}, // Разбивает голову о прутья клетки. rus_verbs:облокотиться{}, // облокотиться о стену rus_verbs:точить{}, // точить о точильный камень rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень rus_verbs:потереться{}, // потереться о дерево rus_verbs:ушибиться{}, // ушибиться о дерево rus_verbs:тереться{}, // тереться о ствол rus_verbs:шмякнуться{}, // шмякнуться о землю rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:тереть{}, // тереть о камень rus_verbs:потереть{}, // потереть о колено rus_verbs:удариться{}, // удариться о край rus_verbs:споткнуться{}, // споткнуться о камень rus_verbs:запнуться{}, // запнуться о камень rus_verbs:запинаться{}, // запинаться о камни rus_verbs:ударяться{}, // ударяться о бортик rus_verbs:стукнуться{}, // стукнуться о бортик rus_verbs:стукаться{}, // стукаться о бортик rus_verbs:опереться{}, // Он опёрся локтями о стол. rus_verbs:плескаться{} // Вода плещется о берег. } fact гл_предл { if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:о{} *:*{ падеж:вин } } then return false,-5 } wordentry_set Гл_О_предл={ rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ) rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ) rus_verbs:РАССПРАШИВАТЬ{}, // rus_verbs:слушать{}, // ты будешь слушать о них? rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ) rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ) rus_verbs:сложить{}, // о вас сложены легенды rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О) rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О) rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О) rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О) rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О) rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О) rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О) rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О) rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О) rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О) rus_verbs:осведомиться{}, // офицер осведомился о цели визита rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о) rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О) rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о) rus_verbs:зайти{}, // Разговор зашёл о политике. rus_verbs:порассказать{}, // порассказать о своих путешествиях инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви деепричастие:спев{}, прилагательное:спевший{ вид:соверш }, прилагательное:спетый{}, rus_verbs:напеть{}, rus_verbs:разговаривать{}, // разговаривать с другом о жизни rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях //rus_verbs:заботиться{}, // заботиться о престарелых родителях rus_verbs:раздумывать{}, // раздумывать о новой работе rus_verbs:договариваться{}, // договариваться о сумме компенсации rus_verbs:молить{}, // молить о пощаде rus_verbs:отзываться{}, // отзываться о книге rus_verbs:подумывать{}, // подумывать о новом подходе rus_verbs:поговаривать{}, // поговаривать о загадочном звере rus_verbs:обмолвиться{}, // обмолвиться о проклятии rus_verbs:условиться{}, // условиться о поддержке rus_verbs:призадуматься{}, // призадуматься о последствиях rus_verbs:известить{}, // известить о поступлении rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:напевать{}, // напевать о любви rus_verbs:помышлять{}, // помышлять о новом деле rus_verbs:переговорить{}, // переговорить о правилах rus_verbs:повествовать{}, // повествовать о событиях rus_verbs:слыхивать{}, // слыхивать о чудище rus_verbs:потолковать{}, // потолковать о планах rus_verbs:проговориться{}, // проговориться о планах rus_verbs:умолчать{}, // умолчать о штрафах rus_verbs:хлопотать{}, // хлопотать о премии rus_verbs:уведомить{}, // уведомить о поступлении rus_verbs:горевать{}, // горевать о потере rus_verbs:запамятовать{}, // запамятовать о важном мероприятии rus_verbs:заикнуться{}, // заикнуться о прибавке rus_verbs:информировать{}, // информировать о событиях rus_verbs:проболтаться{}, // проболтаться о кладе rus_verbs:поразмыслить{}, // поразмыслить о судьбе rus_verbs:заикаться{}, // заикаться о деньгах rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:печься{}, // печься о всеобщем благе rus_verbs:разглагольствовать{}, // разглагольствовать о правах rus_verbs:размечтаться{}, // размечтаться о будущем rus_verbs:лепетать{}, // лепетать о невиновности rus_verbs:грезить{}, // грезить о большой и чистой любви rus_verbs:залепетать{}, // залепетать о сокровищах rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде rus_verbs:протрубить{}, // протрубить о победе rus_verbs:извещать{}, // извещать о поступлении rus_verbs:трубить{}, // трубить о поимке разбойников rus_verbs:осведомляться{}, // осведомляться о судьбе rus_verbs:поразмышлять{}, // поразмышлять о неизбежном rus_verbs:слагать{}, // слагать о подвигах викингов rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании rus_verbs:закидывать{}, // закидывать сообщениями об ошибках rus_verbs:базарить{}, // пацаны базарили о телках rus_verbs:балагурить{}, // мужики балагурили о новом председателе rus_verbs:балакать{}, // мужики балакали о новом председателе rus_verbs:беспокоиться{}, // Она беспокоится о детях rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве rus_verbs:возмечтать{}, // возмечтать о счастливом мире rus_verbs:вопить{}, // Кто-то вопил о несправедливости rus_verbs:сказать{}, // сказать что-то новое о ком-то rus_verbs:знать{}, // знать о ком-то что-то пикантное rus_verbs:подумать{}, // подумать о чём-то rus_verbs:думать{}, // думать о чём-то rus_verbs:узнать{}, // узнать о происшествии rus_verbs:помнить{}, // помнить о задании rus_verbs:просить{}, // просить о коде доступа rus_verbs:забыть{}, // забыть о своих обязанностях rus_verbs:сообщить{}, // сообщить о заложенной мине rus_verbs:заявить{}, // заявить о пропаже rus_verbs:задуматься{}, // задуматься о смерти rus_verbs:спрашивать{}, // спрашивать о поступлении товара rus_verbs:догадаться{}, // догадаться о причинах rus_verbs:договориться{}, // договориться о собеседовании rus_verbs:мечтать{}, // мечтать о сцене rus_verbs:поговорить{}, // поговорить о наболевшем rus_verbs:размышлять{}, // размышлять о насущном rus_verbs:напоминать{}, // напоминать о себе rus_verbs:пожалеть{}, // пожалеть о содеянном rus_verbs:ныть{}, // ныть о прибавке rus_verbs:сообщать{}, // сообщать о победе rus_verbs:догадываться{}, // догадываться о первопричине rus_verbs:поведать{}, // поведать о тайнах rus_verbs:умолять{}, // умолять о пощаде rus_verbs:сожалеть{}, // сожалеть о случившемся rus_verbs:жалеть{}, // жалеть о случившемся rus_verbs:забывать{}, // забывать о случившемся rus_verbs:упоминать{}, // упоминать о предках rus_verbs:позабыть{}, // позабыть о своем обещании rus_verbs:запеть{}, // запеть о любви rus_verbs:скорбеть{}, // скорбеть о усопшем rus_verbs:задумываться{}, // задумываться о смене работы rus_verbs:позаботиться{}, // позаботиться о престарелых родителях rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината rus_verbs:попросить{}, // попросить о замене rus_verbs:предупредить{}, // предупредить о замене rus_verbs:предупреждать{}, // предупреждать о замене rus_verbs:твердить{}, // твердить о замене rus_verbs:заявлять{}, // заявлять о подлоге rus_verbs:петь{}, // певица, поющая о лете rus_verbs:проинформировать{}, // проинформировать о переговорах rus_verbs:порассказывать{}, // порассказывать о событиях rus_verbs:послушать{}, // послушать о новинках rus_verbs:заговорить{}, // заговорить о плате rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой. rus_verbs:оставить{}, // Он оставил о себе печальную память. rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях rus_verbs:спорить{}, // они спорили о законе глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия. глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия. rus_verbs:прочитать{}, // Я прочитал о тебе rus_verbs:услышать{}, // Я услышал о нем rus_verbs:помечтать{}, // Девочки помечтали о принце rus_verbs:слышать{}, // Мальчик слышал о приведениях rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке rus_verbs:грустить{}, // Я грущу о тебе rus_verbs:осведомить{}, // о последних достижениях науки rus_verbs:рассказывать{}, // Антонио рассказывает о работе rus_verbs:говорить{}, // говорим о трех больших псах rus_verbs:идти{} // Вопрос идёт о войне. } fact гл_предл { if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } } then return true } // Мы поделились впечатлениями о выставке. // ^^^^^^^^^^ ^^^^^^^^^^ fact гл_предл { if context { * предлог:о{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:о{} *:*{} } then return false,-5 } #endregion Предлог_О #region Предлог_ПО // ------------------- С ПРЕДЛОГОМ 'ПО' ---------------------- // для этих глаголов - запрещаем связывание с ПО+дат.п. wordentry_set Глаг_ПО_Дат_Запр= { rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:закончить{}, rus_verbs:мочь{}, rus_verbs:хотеть{} } fact гл_предл { if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } } then return false,-10 } // По умолчанию разрешаем связывание в паттернах типа // Я иду по шоссе fact гл_предл { if context { * предлог:по{} *:*{ падеж:дат } } then return true } wordentry_set Глаг_ПО_Вин= { rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ) rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО) rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера rus_verbs:засадить{}, // засадить по рукоятку rus_verbs:увязнуть{} // увязнуть по колено } fact гл_предл { if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:по{} *:*{ падеж:вин } } then return false,-5 } #endregion Предлог_ПО #region Предлог_К // ------------------- С ПРЕДЛОГОМ 'К' ---------------------- wordentry_set Гл_К_Дат={ rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна. rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску. прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ) rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ) rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ) rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ) rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ) rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ) rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ) rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ) rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ) rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, // rus_verbs:ПРИНОРОВИТЬСЯ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ) rus_verbs:СПИКИРОВАТЬ{}, // rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С) rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ) rus_verbs:ПРОТЯНУТЬ{}, // rus_verbs:ТЯНУТЬ{}, // rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ) rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,, rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, // rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, // rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ) rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке. rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ) rus_verbs:хотеть{}, rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ) rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ) rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ) rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ) rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ) rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ) rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ) rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ) rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ) rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ) rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ) rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К) rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К) rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К) rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К) rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К) прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К) безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К) rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К) rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К) rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К) rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К) rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К) rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К) rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К) rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К) rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К) rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К) rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К) rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К) rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К) rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К) rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К) rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К) rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К) rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К) rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К) rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К) rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К) rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К) rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К) глагол:быть{}, // к тебе есть вопросы. прилагательное:равнодушный{}, // Он равнодушен к музыке. rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К) rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К) инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К) rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К) rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к) rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К) rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К) rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К) rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К) rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К) rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К) rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К) rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к) rus_verbs:просить{}, // Директор просит вас к себе. (просить к) rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к) rus_verbs:присесть{}, // старик присел к огню. (присесть к) rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К) rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к) rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к) rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К) rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К) rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К) rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К) rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к) rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К) rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К) rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К) rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К) rus_verbs:подходить{}, // цвет подходил ей к лицу. rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К) rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К) rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К) rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К) rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К) rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К) rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к) rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К) rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К) rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к) rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к) rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К) rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К) rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К) rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К) rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к) rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к) rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к) rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К) rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к) rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к) rus_verbs:требовать{}, // вас требует к себе император. (требовать к) rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к) rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к) rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К) rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К) rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к) rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К) rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К) rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к) rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к) rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к) rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К) rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к) rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к) rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к) rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К) rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К) rus_verbs:выехать{}, // почти сразу мы выехали к реке. rus_verbs:пододвигаться{}, // пододвигайся к окну rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам. rus_verbs:представить{}, // Его представили к ордену. rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу. rus_verbs:выскочить{}, // тем временем они выскочили к реке. rus_verbs:выйти{}, // тем временем они вышли к лестнице. rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе. rus_verbs:приложить{}, // приложить к детали повышенное усилие rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку) rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю rus_verbs:прыгать{}, // прыгать к хозяину на стол rus_verbs:приглашать{}, // приглашать к доктору rus_verbs:рваться{}, // Чужие люди рвутся к власти rus_verbs:понестись{}, // понестись к обрыву rus_verbs:питать{}, // питать привязанность к алкоголю rus_verbs:заехать{}, // Коля заехал к Оле rus_verbs:переехать{}, // переехать к родителям rus_verbs:ползти{}, // ползти к дороге rus_verbs:сводиться{}, // сводиться к элементарному действию rus_verbs:добавлять{}, // добавлять к общей сумме rus_verbs:подбросить{}, // подбросить к потолку rus_verbs:призывать{}, // призывать к спокойствию rus_verbs:пробираться{}, // пробираться к партизанам rus_verbs:отвезти{}, // отвезти к родителям rus_verbs:применяться{}, // применяться к уравнению rus_verbs:сходиться{}, // сходиться к точному решению rus_verbs:допускать{}, // допускать к сдаче зачета rus_verbs:свести{}, // свести к нулю rus_verbs:придвинуть{}, // придвинуть к мальчику rus_verbs:подготовить{}, // подготовить к печати rus_verbs:подобраться{}, // подобраться к оленю rus_verbs:заторопиться{}, // заторопиться к выходу rus_verbs:пристать{}, // пристать к берегу rus_verbs:поманить{}, // поманить к себе rus_verbs:припасть{}, // припасть к алтарю rus_verbs:притащить{}, // притащить к себе домой rus_verbs:прижимать{}, // прижимать к груди rus_verbs:подсесть{}, // подсесть к симпатичной девочке rus_verbs:придвинуться{}, // придвинуться к окну rus_verbs:отпускать{}, // отпускать к другу rus_verbs:пригнуться{}, // пригнуться к земле rus_verbs:пристроиться{}, // пристроиться к колонне rus_verbs:сгрести{}, // сгрести к себе rus_verbs:удрать{}, // удрать к цыганам rus_verbs:прибавиться{}, // прибавиться к общей сумме rus_verbs:присмотреться{}, // присмотреться к покупке rus_verbs:подкатить{}, // подкатить к трюму rus_verbs:клонить{}, // клонить ко сну rus_verbs:проследовать{}, // проследовать к выходу rus_verbs:пододвинуть{}, // пододвинуть к себе rus_verbs:применять{}, // применять к сотрудникам rus_verbs:прильнуть{}, // прильнуть к экранам rus_verbs:подвинуть{}, // подвинуть к себе rus_verbs:примчаться{}, // примчаться к папе rus_verbs:подкрасться{}, // подкрасться к жертве rus_verbs:привязаться{}, // привязаться к собаке rus_verbs:забирать{}, // забирать к себе rus_verbs:прорваться{}, // прорваться к кассе rus_verbs:прикасаться{}, // прикасаться к коже rus_verbs:уносить{}, // уносить к себе rus_verbs:подтянуться{}, // подтянуться к месту rus_verbs:привозить{}, // привозить к ветеринару rus_verbs:подползти{}, // подползти к зайцу rus_verbs:приблизить{}, // приблизить к глазам rus_verbs:применить{}, // применить к уравнению простое преобразование rus_verbs:приглядеться{}, // приглядеться к изображению rus_verbs:приложиться{}, // приложиться к ручке rus_verbs:приставать{}, // приставать к девчонкам rus_verbs:запрещаться{}, // запрещаться к показу rus_verbs:прибегать{}, // прибегать к насилию rus_verbs:побудить{}, // побудить к действиям rus_verbs:притягивать{}, // притягивать к себе rus_verbs:пристроить{}, // пристроить к полезному делу rus_verbs:приговорить{}, // приговорить к смерти rus_verbs:склоняться{}, // склоняться к прекращению разработки rus_verbs:подъезжать{}, // подъезжать к вокзалу rus_verbs:привалиться{}, // привалиться к забору rus_verbs:наклоняться{}, // наклоняться к щенку rus_verbs:подоспеть{}, // подоспеть к обеду rus_verbs:прилипнуть{}, // прилипнуть к окну rus_verbs:приволочь{}, // приволочь к себе rus_verbs:устремляться{}, // устремляться к вершине rus_verbs:откатиться{}, // откатиться к исходным позициям rus_verbs:побуждать{}, // побуждать к действиям rus_verbs:прискакать{}, // прискакать к кормежке rus_verbs:присматриваться{}, // присматриваться к новичку rus_verbs:прижиматься{}, // прижиматься к борту rus_verbs:жаться{}, // жаться к огню rus_verbs:передвинуть{}, // передвинуть к окну rus_verbs:допускаться{}, // допускаться к экзаменам rus_verbs:прикрепить{}, // прикрепить к корпусу rus_verbs:отправлять{}, // отправлять к специалистам rus_verbs:перебежать{}, // перебежать к врагам rus_verbs:притронуться{}, // притронуться к реликвии rus_verbs:заспешить{}, // заспешить к семье rus_verbs:ревновать{}, // ревновать к сопернице rus_verbs:подступить{}, // подступить к горлу rus_verbs:уводить{}, // уводить к ветеринару rus_verbs:побросать{}, // побросать к ногам rus_verbs:подаваться{}, // подаваться к ужину rus_verbs:приписывать{}, // приписывать к достижениям rus_verbs:относить{}, // относить к растениям rus_verbs:принюхаться{}, // принюхаться к ароматам rus_verbs:подтащить{}, // подтащить к себе rus_verbs:прислонить{}, // прислонить к стене rus_verbs:подплыть{}, // подплыть к бую rus_verbs:опаздывать{}, // опаздывать к стилисту rus_verbs:примкнуть{}, // примкнуть к деомнстрантам rus_verbs:стекаться{}, // стекаются к стенам тюрьмы rus_verbs:подготовиться{}, // подготовиться к марафону rus_verbs:приглядываться{}, // приглядываться к новичку rus_verbs:присоединяться{}, // присоединяться к сообществу rus_verbs:клониться{}, // клониться ко сну rus_verbs:привыкать{}, // привыкать к хорошему rus_verbs:принудить{}, // принудить к миру rus_verbs:уплыть{}, // уплыть к далекому берегу rus_verbs:утащить{}, // утащить к детенышам rus_verbs:приплыть{}, // приплыть к финишу rus_verbs:подбегать{}, // подбегать к хозяину rus_verbs:лишаться{}, // лишаться средств к существованию rus_verbs:приступать{}, // приступать к операции rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике rus_verbs:подключить{}, // подключить к трубе rus_verbs:подключиться{}, // подключиться к сети rus_verbs:прилить{}, // прилить к лицу rus_verbs:стучаться{}, // стучаться к соседям rus_verbs:пристегнуть{}, // пристегнуть к креслу rus_verbs:присоединить{}, // присоединить к сети rus_verbs:отбежать{}, // отбежать к противоположной стене rus_verbs:подвезти{}, // подвезти к набережной rus_verbs:прибегнуть{}, // прибегнуть к хитрости rus_verbs:приучить{}, // приучить к туалету rus_verbs:подталкивать{}, // подталкивать к выходу rus_verbs:прорываться{}, // прорываться к выходу rus_verbs:увозить{}, // увозить к ветеринару rus_verbs:засеменить{}, // засеменить к выходу rus_verbs:крепиться{}, // крепиться к потолку rus_verbs:прибрать{}, // прибрать к рукам rus_verbs:пристраститься{}, // пристраститься к наркотикам rus_verbs:поспеть{}, // поспеть к обеду rus_verbs:привязывать{}, // привязывать к дереву rus_verbs:прилагать{}, // прилагать к документам rus_verbs:переправить{}, // переправить к дедушке rus_verbs:подогнать{}, // подогнать к воротам rus_verbs:тяготеть{}, // тяготеть к социализму rus_verbs:подбираться{}, // подбираться к оленю rus_verbs:подступать{}, // подступать к горлу rus_verbs:примыкать{}, // примыкать к первому элементу rus_verbs:приладить{}, // приладить к велосипеду rus_verbs:подбрасывать{}, // подбрасывать к потолку rus_verbs:перевозить{}, // перевозить к новому месту дислокации rus_verbs:усаживаться{}, // усаживаться к окну rus_verbs:приближать{}, // приближать к глазам rus_verbs:попроситься{}, // попроситься к бабушке rus_verbs:прибить{}, // прибить к доске rus_verbs:перетащить{}, // перетащить к себе rus_verbs:прицепить{}, // прицепить к паровозу rus_verbs:прикладывать{}, // прикладывать к ране rus_verbs:устареть{}, // устареть к началу войны rus_verbs:причалить{}, // причалить к пристани rus_verbs:приспособиться{}, // приспособиться к опозданиям rus_verbs:принуждать{}, // принуждать к миру rus_verbs:соваться{}, // соваться к директору rus_verbs:протолкаться{}, // протолкаться к прилавку rus_verbs:приковать{}, // приковать к батарее rus_verbs:подкрадываться{}, // подкрадываться к суслику rus_verbs:подсадить{}, // подсадить к арестонту rus_verbs:прикатить{}, // прикатить к финишу rus_verbs:протащить{}, // протащить к владыке rus_verbs:сужаться{}, // сужаться к основанию rus_verbs:присовокупить{}, // присовокупить к пожеланиям rus_verbs:пригвоздить{}, // пригвоздить к доске rus_verbs:отсылать{}, // отсылать к первоисточнику rus_verbs:изготовиться{}, // изготовиться к прыжку rus_verbs:прилагаться{}, // прилагаться к покупке rus_verbs:прицепиться{}, // прицепиться к вагону rus_verbs:примешиваться{}, // примешиваться к вину rus_verbs:переселить{}, // переселить к старшекурсникам rus_verbs:затрусить{}, // затрусить к выходе rus_verbs:приспособить{}, // приспособить к обогреву rus_verbs:примериться{}, // примериться к аппарату rus_verbs:прибавляться{}, // прибавляться к пенсии rus_verbs:подкатиться{}, // подкатиться к воротам rus_verbs:стягивать{}, // стягивать к границе rus_verbs:дописать{}, // дописать к роману rus_verbs:подпустить{}, // подпустить к корове rus_verbs:склонять{}, // склонять к сотрудничеству rus_verbs:припечатать{}, // припечатать к стене rus_verbs:охладеть{}, // охладеть к музыке rus_verbs:пришить{}, // пришить к шинели rus_verbs:принюхиваться{}, // принюхиваться к ветру rus_verbs:подрулить{}, // подрулить к барышне rus_verbs:наведаться{}, // наведаться к оракулу rus_verbs:клеиться{}, // клеиться к конверту rus_verbs:перетянуть{}, // перетянуть к себе rus_verbs:переметнуться{}, // переметнуться к конкурентам rus_verbs:липнуть{}, // липнуть к сокурсницам rus_verbs:поковырять{}, // поковырять к выходу rus_verbs:подпускать{}, // подпускать к пульту управления rus_verbs:присосаться{}, // присосаться к источнику rus_verbs:приклеить{}, // приклеить к стеклу rus_verbs:подтягивать{}, // подтягивать к себе rus_verbs:подкатывать{}, // подкатывать к даме rus_verbs:притрагиваться{}, // притрагиваться к опухоли rus_verbs:слетаться{}, // слетаться к водопою rus_verbs:хаживать{}, // хаживать к батюшке rus_verbs:привлекаться{}, // привлекаться к административной ответственности rus_verbs:подзывать{}, // подзывать к себе rus_verbs:прикладываться{}, // прикладываться к иконе rus_verbs:подтягиваться{}, // подтягиваться к парламенту rus_verbs:прилепить{}, // прилепить к стенке холодильника rus_verbs:пододвинуться{}, // пододвинуться к экрану rus_verbs:приползти{}, // приползти к дереву rus_verbs:запаздывать{}, // запаздывать к обеду rus_verbs:припереть{}, // припереть к стене rus_verbs:нагибаться{}, // нагибаться к цветку инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам деепричастие:сгоняв{}, rus_verbs:поковылять{}, // поковылять к выходу rus_verbs:привалить{}, // привалить к столбу rus_verbs:отпроситься{}, // отпроситься к родителям rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям rus_verbs:прилипать{}, // прилипать к рукам rus_verbs:подсоединить{}, // подсоединить к приборам rus_verbs:приливать{}, // приливать к голове rus_verbs:подселить{}, // подселить к другим новичкам rus_verbs:прилепиться{}, // прилепиться к шкуре rus_verbs:подлетать{}, // подлетать к пункту назначения rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг rus_verbs:льнуть{}, // льнуть к заботливому хозяину rus_verbs:привязываться{}, // привязываться к любящему хозяину rus_verbs:приклеиться{}, // приклеиться к спине rus_verbs:стягиваться{}, // стягиваться к сенату rus_verbs:подготавливать{}, // подготавливать к выходу на арену rus_verbs:приглашаться{}, // приглашаться к доктору rus_verbs:причислять{}, // причислять к отличникам rus_verbs:приколоть{}, // приколоть к лацкану rus_verbs:наклонять{}, // наклонять к горизонту rus_verbs:припадать{}, // припадать к первоисточнику rus_verbs:приобщиться{}, // приобщиться к культурному наследию rus_verbs:придираться{}, // придираться к мелким ошибкам rus_verbs:приучать{}, // приучать к лотку rus_verbs:промотать{}, // промотать к началу rus_verbs:прихлынуть{}, // прихлынуть к голове rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу rus_verbs:прикрутить{}, // прикрутить к велосипеду rus_verbs:подплывать{}, // подплывать к лодке rus_verbs:приравниваться{}, // приравниваться к побегу rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы rus_verbs:приткнуться{}, // приткнуться к первой группе туристов rus_verbs:приручить{}, // приручить котика к лотку rus_verbs:приковывать{}, // приковывать к себе все внимание прессы rus_verbs:приготовляться{}, // приготовляться к первому экзамену rus_verbs:остыть{}, // Вода остынет к утру. rus_verbs:приехать{}, // Он приедет к концу будущей недели. rus_verbs:подсаживаться{}, rus_verbs:успевать{}, // успевать к стилисту rus_verbs:привлекать{}, // привлекать к себе внимание прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму rus_verbs:прийтись{}, // прийтись ко двору инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы инфинитив:адаптироваться{вид:несоверш}, глагол:адаптироваться{вид:соверш}, глагол:адаптироваться{вид:несоверш}, деепричастие:адаптировавшись{}, деепричастие:адаптируясь{}, прилагательное:адаптировавшийся{вид:соверш}, //+прилагательное:адаптировавшийся{вид:несоверш}, прилагательное:адаптирующийся{}, rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей rus_verbs:близиться{}, // Шторм близится к побережью rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки rus_verbs:причислить{}, // Мы причислили его к числу экспертов rus_verbs:вести{}, // Наша партия ведет народ к процветанию rus_verbs:взывать{}, // Учителя взывают к совести хулигана rus_verbs:воззвать{}, // воззвать соплеменников к оружию rus_verbs:возревновать{}, // возревновать к поклонникам rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью rus_verbs:восходить{}, // восходить к вершине rus_verbs:восшествовать{}, // восшествовать к вершине rus_verbs:успеть{}, // успеть к обеду rus_verbs:повернуться{}, // повернуться к кому-то rus_verbs:обратиться{}, // обратиться к охраннику rus_verbs:звать{}, // звать к столу rus_verbs:отправиться{}, // отправиться к парикмахеру rus_verbs:обернуться{}, // обернуться к зовущему rus_verbs:явиться{}, // явиться к следователю rus_verbs:уехать{}, // уехать к родне rus_verbs:прибыть{}, // прибыть к перекличке rus_verbs:привыкнуть{}, // привыкнуть к голоду rus_verbs:уходить{}, // уходить к цыганам rus_verbs:привести{}, // привести к себе rus_verbs:шагнуть{}, // шагнуть к славе rus_verbs:относиться{}, // относиться к прежним периодам rus_verbs:подослать{}, // подослать к врагам rus_verbs:поспешить{}, // поспешить к обеду rus_verbs:зайти{}, // зайти к подруге rus_verbs:позвать{}, // позвать к себе rus_verbs:потянуться{}, // потянуться к рычагам rus_verbs:пускать{}, // пускать к себе rus_verbs:отвести{}, // отвести к врачу rus_verbs:приблизиться{}, // приблизиться к решению задачи rus_verbs:прижать{}, // прижать к стене rus_verbs:отправить{}, // отправить к доктору rus_verbs:падать{}, // падать к многолетним минимумам rus_verbs:полезть{}, // полезть к дерущимся rus_verbs:лезть{}, // Ты сама ко мне лезла! rus_verbs:направить{}, // направить к майору rus_verbs:приводить{}, // приводить к дантисту rus_verbs:кинуться{}, // кинуться к двери rus_verbs:поднести{}, // поднести к глазам rus_verbs:подниматься{}, // подниматься к себе rus_verbs:прибавить{}, // прибавить к результату rus_verbs:зашагать{}, // зашагать к выходу rus_verbs:склониться{}, // склониться к земле rus_verbs:стремиться{}, // стремиться к вершине rus_verbs:лететь{}, // лететь к родственникам rus_verbs:ездить{}, // ездить к любовнице rus_verbs:приближаться{}, // приближаться к финише rus_verbs:помчаться{}, // помчаться к стоматологу rus_verbs:прислушаться{}, // прислушаться к происходящему rus_verbs:изменить{}, // изменить к лучшему собственную жизнь rus_verbs:проявить{}, // проявить к погибшим сострадание rus_verbs:подбежать{}, // подбежать к упавшему rus_verbs:терять{}, // терять к партнерам доверие rus_verbs:пропустить{}, // пропустить к певцу rus_verbs:подвести{}, // подвести к глазам rus_verbs:меняться{}, // меняться к лучшему rus_verbs:заходить{}, // заходить к другу rus_verbs:рвануться{}, // рвануться к воде rus_verbs:привлечь{}, // привлечь к себе внимание rus_verbs:присоединиться{}, // присоединиться к сети rus_verbs:приезжать{}, // приезжать к дедушке rus_verbs:дернуться{}, // дернуться к борту rus_verbs:подъехать{}, // подъехать к воротам rus_verbs:готовиться{}, // готовиться к дождю rus_verbs:убежать{}, // убежать к маме rus_verbs:поднимать{}, // поднимать к источнику сигнала rus_verbs:отослать{}, // отослать к руководителю rus_verbs:приготовиться{}, // приготовиться к худшему rus_verbs:приступить{}, // приступить к выполнению обязанностей rus_verbs:метнуться{}, // метнуться к фонтану rus_verbs:прислушиваться{}, // прислушиваться к голосу разума rus_verbs:побрести{}, // побрести к выходу rus_verbs:мчаться{}, // мчаться к успеху rus_verbs:нестись{}, // нестись к обрыву rus_verbs:попадать{}, // попадать к хорошему костоправу rus_verbs:опоздать{}, // опоздать к психотерапевту rus_verbs:посылать{}, // посылать к доктору rus_verbs:поплыть{}, // поплыть к берегу rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе rus_verbs:отнести{}, // отнести животное к ветеринару rus_verbs:прислониться{}, // прислониться к стволу rus_verbs:наклонить{}, // наклонить к миске с молоком rus_verbs:прикоснуться{}, // прикоснуться к поверхности rus_verbs:увезти{}, // увезти к бабушке rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия rus_verbs:подозвать{}, // подозвать к себе rus_verbs:улететь{}, // улететь к теплым берегам rus_verbs:ложиться{}, // ложиться к мужу rus_verbs:убираться{}, // убираться к чертовой бабушке rus_verbs:класть{}, // класть к другим документам rus_verbs:доставлять{}, // доставлять к подъезду rus_verbs:поворачиваться{}, // поворачиваться к источнику шума rus_verbs:заглядывать{}, // заглядывать к любовнице rus_verbs:занести{}, // занести к заказчикам rus_verbs:прибежать{}, // прибежать к папе rus_verbs:притянуть{}, // притянуть к причалу rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:подать{}, // он подал лимузин к подъезду rus_verbs:подавать{}, // она подавала соус к мясу rus_verbs:приобщаться{}, // приобщаться к культуре прилагательное:неспособный{}, // Наша дочка неспособна к учению. прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару прилагательное:предназначенный{}, // Старый дом предназначен к сносу. прилагательное:внимательный{}, // Она всегда внимательна к гостям. прилагательное:назначенный{}, // Дело назначено к докладу. прилагательное:разрешенный{}, // Эта книга разрешена к печати. прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам. прилагательное:готовый{}, // Я готов к экзаменам. прилагательное:требовательный{}, // Он очень требователен к себе. прилагательное:жадный{}, // Он жаден к деньгам. прилагательное:глухой{}, // Он глух к моей просьбе. прилагательное:добрый{}, // Он добр к детям. rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам. rus_verbs:плыть{}, // Пароход плыл к берегу. rus_verbs:пойти{}, // я пошел к доктору rus_verbs:придти{}, // придти к выводу rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом. rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений. rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам. rus_verbs:спускаться{}, // Улица круто спускается к реке. rus_verbs:спуститься{}, // Мы спустились к реке. rus_verbs:пустить{}, // пускать ко дну rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью! rus_verbs:отойти{}, // Дом отошёл к племяннику. rus_verbs:отходить{}, // Коля отходил ко сну. rus_verbs:приходить{}, // местные жители к нему приходили лечиться rus_verbs:кидаться{}, // не кидайся к столу rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу. rus_verbs:закончиться{}, // Собрание закончилось к вечеру. rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему. rus_verbs:направиться{}, // Мы сошли на берег и направились к городу. rus_verbs:направляться{}, rus_verbs:свестись{}, // Всё свелось к нулю. rus_verbs:прислать{}, // Пришлите кого-нибудь к ней. rus_verbs:присылать{}, // Он присылал к должнику своих головорезов rus_verbs:подлететь{}, // Самолёт подлетел к лесу. rus_verbs:возвращаться{}, // он возвращается к старой работе глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая. rus_verbs:возвращать{}, // возвращать к жизни rus_verbs:располагать{}, // Атмосфера располагает к работе. rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому. rus_verbs:поступить{}, // К нам поступила жалоба. rus_verbs:поступать{}, // К нам поступают жалобы. rus_verbs:прыгнуть{}, // Белка прыгнула к дереву rus_verbs:торопиться{}, // пассажиры торопятся к выходу rus_verbs:поторопиться{}, // поторопитесь к выходу rus_verbs:вернуть{}, // вернуть к активной жизни rus_verbs:припирать{}, // припирать к стенке rus_verbs:проваливать{}, // Проваливай ко всем чертям! rus_verbs:вбежать{}, // Коля вбежал ко мне rus_verbs:вбегать{}, // Коля вбегал ко мне глагол:забегать{ вид:несоверш }, // Коля забегал ко мне rus_verbs:постучаться{}, // Коля постучался ко мне. rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому rus_verbs:понести{}, // Мы понесли кота к ветеринару rus_verbs:принести{}, // Я принес кота к ветеринару rus_verbs:устремиться{}, // Мы устремились к ручью. rus_verbs:подводить{}, // Учитель подводил детей к аквариуму rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения. rus_verbs:пригласить{}, // Я пригласил к себе товарищей. rus_verbs:собираться{}, // Я собираюсь к тебе в гости. rus_verbs:собраться{}, // Маша собралась к дантисту rus_verbs:сходить{}, // Я схожу к врачу. rus_verbs:идти{}, // Маша уверенно шла к Пете rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию. rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию. rus_verbs:заканчивать{}, // Заканчивайте к обеду rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:окончить{}, // rus_verbs:дозвониться{}, // Я не мог к вам дозвониться. глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор rus_verbs:уйти{}, // Антонио ушел к Элеонор rus_verbs:бежать{}, // Антонио бежит к Элеонор rus_verbs:спешить{}, // Антонио спешит к Элеонор rus_verbs:скакать{}, // Антонио скачет к Элеонор rus_verbs:красться{}, // Антонио крадётся к Элеонор rus_verbs:поскакать{}, // беглецы поскакали к холмам rus_verbs:перейти{} // Антонио перешел к Элеонор } fact гл_предл { if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } } then return true } fact гл_предл { if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:к{} *:*{} } then return false,-5 } #endregion Предлог_К #region Предлог_ДЛЯ // ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ---------------------- wordentry_set Гл_ДЛЯ_Род={ частица:нет{}, // для меня нет других путей. частица:нету{}, rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ) rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ) rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться) rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ) rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ) rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ) rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ) rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ) rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ) rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ) rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ) rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ) rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ) rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ) rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ) rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ) rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ) rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ) rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ) rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ) rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ) rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ) rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ) rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ) rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ) rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ) rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ) rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ) прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ) rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ) rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ) rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ) rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ) rus_verbs:оставить{}, // или вообще решили оставить планету для себя rus_verbs:оставлять{}, rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ) rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ) rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ) rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ) rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ) rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ) rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ) rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ) rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для) rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ) rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ) rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ) rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ) rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ) прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ) прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ) прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ) rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ) rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ) rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ) rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ) rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ) rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ) rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ) rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ) rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ) rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ) rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ) rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ) прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ) rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ) rus_verbs:вывести{}, // мы специально вывели этих животных для мяса. rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для) rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ) rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ) rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ) rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ) rus_verbs:найтись{}, // у вас найдется для него работа? rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для) rus_verbs:заехать{}, // Коля заехал для обсуждения проекта rus_verbs:созреть{}, // созреть для побега rus_verbs:наметить{}, // наметить для проверки rus_verbs:уяснить{}, // уяснить для себя rus_verbs:нанимать{}, // нанимать для разовой работы rus_verbs:приспособить{}, // приспособить для удовольствия rus_verbs:облюбовать{}, // облюбовать для посиделок rus_verbs:прояснить{}, // прояснить для себя rus_verbs:задействовать{}, // задействовать для патрулирования rus_verbs:приготовлять{}, // приготовлять для проверки инфинитив:использовать{ вид:соверш }, // использовать для достижения цели инфинитив:использовать{ вид:несоверш }, глагол:использовать{ вид:соверш }, глагол:использовать{ вид:несоверш }, прилагательное:использованный{}, деепричастие:используя{}, деепричастие:использовав{}, rus_verbs:напрячься{}, // напрячься для решительного рывка rus_verbs:одобрить{}, // одобрить для использования rus_verbs:одобрять{}, // одобрять для использования rus_verbs:пригодиться{}, // пригодиться для тестирования rus_verbs:готовить{}, // готовить для выхода в свет rus_verbs:отобрать{}, // отобрать для участия в конкурсе rus_verbs:потребоваться{}, // потребоваться для подтверждения rus_verbs:пояснить{}, // пояснить для слушателей rus_verbs:пояснять{}, // пояснить для экзаменаторов rus_verbs:понадобиться{}, // понадобиться для обоснования инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, rus_verbs:найти{}, // Папа нашел для детей няню прилагательное:вредный{}, // Это вредно для здоровья. прилагательное:полезный{}, // Прогулки полезны для здоровья. прилагательное:обязательный{}, // Этот пункт обязателен для исполнения прилагательное:бесполезный{}, // Это лекарство бесполезно для него прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления rus_verbs:создать{}, // Он не создан для этого дела. прилагательное:сложный{}, // задача сложна для младших школьников прилагательное:несложный{}, прилагательное:лёгкий{}, прилагательное:сложноватый{}, rus_verbs:становиться{}, rus_verbs:представлять{}, // Это не представляет для меня интереса. rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка rus_verbs:пройти{}, // День прошёл спокойно для него. rus_verbs:проходить{}, rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ rus_verbs:высаживаться{}, rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца. rus_verbs:прибавить{}, rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов. rus_verbs:составлять{}, rus_verbs:стараться{}, // Я старался для вас rus_verbs:постараться{}, // Я постарался для вас rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста. rus_verbs:собраться{}, // собраться для обсуждения rus_verbs:собираться{}, // собираться для обсуждения rus_verbs:уполномочивать{}, rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров rus_verbs:принести{}, // Я принёс эту книгу для вас. rus_verbs:делать{}, // Я это делаю для удовольствия. rus_verbs:сделать{}, // Я сделаю это для удовольствия. rus_verbs:подготовить{}, // я подготовил для друзей сюрприз rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села rus_verbs:прибыть{} // они прибыли для участия } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } } then return true } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:для{} *:*{} } then return false,-4 } #endregion Предлог_ДЛЯ #region Предлог_ОТ // попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_ОТ_Род_Запр= { rus_verbs:наслаждаться{}, // свободой от обязательств rus_verbs:насладиться{}, rus_verbs:мочь{}, // Он не мог удержаться от смеха. // rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:чувствовать{}, // все время от времени чувствуют его. rus_verbs:планировать{}, rus_verbs:приняться{} // мы принялись обниматься от радости. } fact гл_предл { if context { Глаг_ОТ_Род_Запр предлог:от{} * } then return false } #endregion Предлог_ОТ #region Предлог_БЕЗ /* // запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_БЕЗ_Род_Запр= { rus_verbs:мочь{}, // Он мог читать часами без отдыха. rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:планировать{}, rus_verbs:приняться{} } fact гл_предл { if context { Глаг_БЕЗ_Род_Запр предлог:без{} * } then return false } */ #endregion Предлог_БЕЗ #region Предлог_КРОМЕ fact гл_предл { if context { * ПредлогДляВсе * } then return false,-5 } #endregion Предлог_КРОМЕ // ------------------------------------ // По умолчанию разрешаем все остальные сочетания. fact гл_предл { if context { * * * } then return true }
перекликаться с другой статьей
rus_verbs:перекликаться{},
5,486,785
[ 1, 145, 128, 145, 118, 146, 227, 145, 118, 145, 123, 145, 124, 145, 121, 145, 123, 145, 113, 146, 229, 146, 239, 146, 228, 146, 242, 225, 146, 228, 225, 145, 117, 146, 227, 146, 230, 145, 116, 145, 127, 145, 122, 225, 146, 228, 146, 229, 145, 113, 146, 229, 146, 239, 145, 118, 145, 122, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 436, 407, 67, 502, 2038, 30, 145, 128, 145, 118, 146, 227, 145, 118, 145, 123, 145, 124, 145, 121, 145, 123, 145, 113, 146, 229, 146, 239, 146, 228, 146, 242, 2916, 16, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
automat sg { tag наречие:на самом деле{ ТИП_МОДИФ:ГЛАГ } tag наречие:там{ ТИП_МОДИФ:ГЛАГ } tag наречие:воровски{ ТИП_МОДИФ:ГЛАГ } // Бегают воровски черные злые глаза. tag наречие:последовательно{ ТИП_МОДИФ:ГЛАГ } // Выдавить последовательно пустотелую деталь дисковым роликом tag наречие:невдалеке{ ТИП_МОДИФ:ГЛАГ } // Она слышала невдалеке глубокое мерное дыхание. tag наречие:шутя{ ТИП_МОДИФ:ГЛАГ } // Шутя несчастных и счастливых Вертушки милые творят. tag наречие:чай{ ТИП_МОДИФ:ГЛАГ } tag наречие:ежегодно{ ТИП_МОДИФ:ГЛАГ } // Ежегодно каждый класс проводил Праздник книги. tag наречие:ежедневно{ ТИП_МОДИФ:ГЛАГ } // Ежедневно специальные поезда подвозят гурты скота; tag наречие:еженочно{ ТИП_МОДИФ:ГЛАГ } tag наречие:легко{ ТИП_МОДИФ:ГЛАГ } tag наречие:тяжело{ ТИП_МОДИФ:ГЛАГ } tag наречие:трудно{ ТИП_МОДИФ:ГЛАГ } tag наречие:регулярно{ ТИП_МОДИФ:ГЛАГ } // Посещаете ли вы регулярно баню или сауну? tag наречие:непосильно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Все остальные регионы также могут привлекать средства, но цена таких привлечений может оказаться непосильно высокой tag наречие:отчаянно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // А хозяйству отчаянно нужны были пастухи. tag наречие:чудовищно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // И вот возникает чудовищно простой вопрос tag наречие:постепенно{ ТИП_МОДИФ:ГЛАГ } // Постепенно наш футбол пришел в упадок. tag наречие:чисто{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // В нем была чисто мужская привлекательность. tag наречие:стабильно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // Компания приносит стабильно высокий доход. tag наречие:внутренне{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // В этом есть что-то внутренне безобразное. tag наречие:безгранично{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // Он чувствовал себя безгранично униженным. tag наречие:специально{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // Для этого есть специально обученные люди. tag наречие:чудесно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // Воздух был чудесно прохладным и приятным. tag наречие:жизненно{ТИП_МОДИФ:ПРИЛ} // Для него это становилось жизненно важным. tag наречие:празднично{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // В школу ребята пришли празднично одетые. tag наречие:ослепительно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // В небе сияло ослепительно яркое солнце. tag наречие:по-летнему{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // А теперь дни стали по-летнему длинными. tag наречие:прямо-таки{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // в ней царит прямо-таки неземная тишина. tag наречие:необыкновенно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ} // Вечер был необыкновенно жарким и тихим. tag наречие:неумолимо{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ} // В Дэве было что-то неумолимо жестокое. tag наречие:скоро{ ТИП_МОДИФ:ГЛАГ } // Увезите же меня поскор куда-нибудь! tag наречие:необыкновенно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ} // необыкновенно tag наречие:безумно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Он был безумно одинокий человек ... tag наречие:нескончаемо{ТИП_МОДИФ:ПРИЛ} // Дорога кажется нескончаемо долгой. tag наречие:мучительно{ТИП_МОДИФ:ПРИЛ} // Что кажется глубоко символичным. tag наречие:мучительно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ} // Мой приезд был вдвойне роковым. tag наречие:мучительно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // ночь была мучительно долгой tag наречие:чуток{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Но успели ободрать носик чуток! tag наречие:Внешне{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Внешне притихший Салидар на самом деле бурлил. tag наречие:культурологически{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Этическая позиция является культурологически нейтральной. tag наречие:рекордно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Орловские избиратели проявили рекордно высокую активность tag наречие:богатырски { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Рождаются богатырски сильные быстрые ноги. tag наречие:смутно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Его лицо мне показалось смутно знакомым. tag наречие:политически { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его выступление было признано политически ошибочным. tag наречие:по-детски { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его лицо было сейчас по-детски простодушным. tag наречие:безупречно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его лицо хранило безупречно равнодушную мину. tag наречие:возмутительно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его слова показались ей возмутительно самоуверенными. tag наречие:откровенно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его улыбка показалась ей откровенно порочной. tag наречие:правдоподобно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его глаза были не правдоподобно голубыми. tag наречие:экологически{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ } // Принцип нашего канала - экологически чистое телевидение. tag наречие:Своего рода { ТИП_МОДИФ:ПРИЛ } // Своего рода спортивный подвиг совершила наша Елена Соколова. tag наречие:Божественно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Моя душа сразу заново рождается Божественно здоровой. tag наречие:чрезмерно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Можно возразить, что это чрезмерно пессимистическая оценка. tag наречие:идеально { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // tag наречие:необычайно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ } // В нем было что-то необычайно дружелюбное. tag наречие:Особо{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Особо интересных сюжетных поворотов ждать не стоит. tag наречие:страшно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // А теперь чувствовала себя страшно опустошенной. tag наречие:неизъяснимо{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // В этом было что-то неизъяснимо притягательное. tag наречие:пунктуально{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Есть также пунктуально деловитые попрошайки. tag наречие:существенно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Остальным достались существенно меньшие доли. tag наречие:разочаровывающе{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Матч получился разочаровывающе скучным. tag наречие:еле{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Ее обескровленное лицо было пугающе белым. tag наречие:подряд{ ТИП_МОДИФ:ГЛАГ } // Ели все подряд долго и досыта... tag наречие:еле{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Еле слышный вздох вырвался у Клэр. tag наречие:поистине{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Ей присуща была поистине детская непосредственность. tag наречие:неправдоподобно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:особенно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Ее матоватая кожа казалась особенно бледной. tag наречие:ужасающе{ ТИП_МОДИФ:ПРИЛ } // Ее нехитрая одежда была ужасающе грязной. tag наречие:неудовлетворительно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Неудовлетворительно низкой является инновационная активность. tag наречие:несказанно{ ТИП_МОДИФ:ПРИЛ } // В нем было что-то несказанно привлекательное. tag наречие:истинно{ ТИП_МОДИФ:ПРИЛ } // В вас есть истинно славянский шарм! tag наречие:по-настоящему{ ТИП_МОДИФ:ПРИЛ } // Ему не выдержать по-настоящему крупного шторма. tag наречие:патриотически{ ТИП_МОДИФ:ПРИЛ } // Ее активистам подарил патриотически настроенный одессит. tag наречие:несколько{ ТИП_МОДИФ:ПРИЛ } // Ее лицо приобрело несколько смущенное выражение. tag наречие:возбуждающе{ ТИП_МОДИФ:ПРИЛ } // Ее голос снова стал возбуждающе хриплым. tag наречие:смертельно{ ТИП_МОДИФ:ПРИЛ } // Ее лицо было по-прежнему смертельно бледным. tag наречие:весело{ ТИП_МОДИФ:ПРИЛ } // Ее внимание привлекли весело мигающие огоньки. tag наречие:непередаваемо{ ТИП_МОДИФ:ПРИЛ } // Ее глаза приняли непередаваемо синий цвет. tag наречие:невыразимо{ ТИП_МОДИФ:ПРИЛ } tag наречие:в высшей степени{ ТИП_МОДИФ:ПРИЛ } // Ее рассказ показался мне в высшей степени фантастическим. tag наречие:обжигающе{ ТИП_МОДИФ:ПРИЛ } // Ее пронзил обжигающе ледяной клинок силы. tag наречие:социально{ ТИП_МОДИФ:ПРИЛ } // Приоритет отдается социально значимым объектам. tag наречие:сугубо{ ТИП_МОДИФ:ПРИЛ } // Более полутора веков орден был сугубо мужским. tag наречие:заведомо{ ТИП_МОДИФ:ПРИЛ } // Поэтому курс окажется заведомо низким. tag наречие:Некогда{ ТИП_МОДИФ:ПРИЛ } // Некогда сияющие краски померкли. tag наречие:Аномально{ ТИП_МОДИФ:ПРИЛ } // Аномально теплая погода наблюдается в Бурятии tag наречие:срочно{ ТИП_МОДИФ:ГЛАГ } tag наречие:немедленно{ ТИП_МОДИФ:ГЛАГ } // эти наречия выступают в роли модификаторов наречий tag наречие:кричаще{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // В ней все было кричаще вульгарно. tag наречие:болезненно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // В огромном помещении было болезненно тихо. tag наречие:нарочито{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // При этом она действовала нарочито медленно. tag наречие:буквально{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // оно появилось буквально ниоткуда. tag наречие:неестественно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // живые зеленые глаза смотрели неестественно печально tag наречие:прямо{ ТИП_МОДИФ:НАРЕЧ } tag наречие:как-то{ ТИП_МОДИФ:НАРЕЧ } // пришел-то он как-то по-паучьи. tag наречие:так{ ТИП_МОДИФ:НАРЕЧ } // так приятно сделать другу подарок tag наречие:столь{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // прошло столь много лет! tag наречие:настолько{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // В комнате отдыха было настолько темно tag наречие:насколько{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Насколько просто купить оружие в Техасе? tag наречие:вполне{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:по крайней мере{ ТИП_МОДИФ:НАРЕЧ } // по крайней мере так ему сказали tag наречие:почти{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:чуть{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // тонкие губы лесного стрелка чуть заметно дрогнули. tag наречие:совсем{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:слишком{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:словно{ ТИП_МОДИФ:НАРЕЧ } // страх пришел словно извне. tag наречие:неожиданно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // однако камень поднялся неожиданно легко. tag наречие:просто{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // мои колени чувствуют себя просто великолепно tag наречие:хоть{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:ПРИЛ } // постарайтесь теперь поспать хоть немного tag наречие:даже{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ГЛАГ } // мне жаль тебя даже сейчас tag наречие:абсолютно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // остальные выглядели абсолютно нормально. tag наречие:относительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // первый час прошел относительно тихо. tag наречие:довольно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // довольно скоро донесся шум двигателей. tag наречие:сравнительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // писать начал сравнительно недавно. tag наречие:действительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // идти пришлось действительно недалеко. tag наречие:невыносимо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // обед тянулся невыносимо долго. tag наречие:бесконечно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // молчание тянулось бесконечно долго. tag наречие:угрожающе{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // стены проносились угрожающе близко. tag наречие:совершенно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:ничуть{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:очень{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:весьма{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:крайне{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:исключительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:достаточно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:чрезвычайно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} tag наречие:нестерпимо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Было нестерпимо душно. tag наречие:неимоверно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // Было неимоверно трудно. tag наречие:чертовски{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} tag наречие:максимально{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:более{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } tag наречие:менее{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } tag наречие:недопустимо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:неприемлемо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:невероятно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:невозможно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:невообразимо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:фантастически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:сногсшибательно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:феерически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:охуительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:уже{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:"все еще"{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:практически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:юридически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:логически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:чересчур{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:физически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } tag наречие:едва{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} tag наречие:немного{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:чуточку{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:только{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ГЛАГ } tag наречие:еле{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } tag наречие:особенно{ ТИП_МОДИФ:НАРЕЧ } // вдруг свет вспыхнул особенно ярко. tag наречие:ужасно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // вдруг стало ужасно тихо. tag наречие:эстетически{ ТИП_МОДИФ:НАРЕЧ } // сделать это эстетически верно tag наречие:непривычно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // дверь за ними захлопнулась непривычно тихо. tag наречие:вызывающе{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Одевается вызывающе броско. // Эта группа наречий может атрибутировать модификаторы наречий: // Он поет уже очень долго // ^^^ tag наречие:уже{ ТИП_МОДИФ:НАРЕЧ0 } // она длилась уже так долго tag наречие:почти{ ТИП_МОДИФ:НАРЕЧ0 } tag наречие:иногда{ ТИП_МОДИФ:НАРЕЧ0 } tag наречие:временами{ ТИП_МОДИФ:НАРЕЧ0 } tag наречие:сначала{ ТИП_МОДИФ:НАРЕЧ0 } tag наречие:затем{ ТИП_МОДИФ:НАРЕЧ0 } tag наречие:"в конце концов"{ ТИП_МОДИФ:НАРЕЧ0 } tag наречие:наконец{ ТИП_МОДИФ:НАРЕЧ0 } // Эти наречия могут модифицировать существительное в родительном падеже: tag наречие:полно{ ТИП_МОДИФ:СУЩ } // у него было полно работы tag наречие:полным-полно{ ТИП_МОДИФ:СУЩ } // В замке было полным-полно его слуг. tag наречие:столько{ ТИП_МОДИФ:СУЩ } tag наречие:сколько{ ТИП_МОДИФ:СУЩ } tag наречие:сколько-то{ ТИП_МОДИФ:СУЩ } tag наречие:столько-то{ ТИП_МОДИФ:СУЩ } // Столько-то красок и времени - столько-то денег. tag наречие:несколько{ ТИП_МОДИФ:СУЩ } tag наречие:много{ ТИП_МОДИФ:СУЩ } tag наречие:невпроворот{ ТИП_МОДИФ:СУЩ } // А я поеду, дел невпроворот. tag наречие:дохера{ ТИП_МОДИФ:СУЩ } tag наречие:дохерища{ ТИП_МОДИФ:СУЩ } tag наречие:дофига{ ТИП_МОДИФ:СУЩ } tag наречие:дофигища{ ТИП_МОДИФ:СУЩ } tag наречие:дохуя{ ТИП_МОДИФ:СУЩ } tag наречие:дохуища{ ТИП_МОДИФ:СУЩ } tag наречие:больше всего{ ТИП_МОДИФ:СУЩ } // Больше всего аварий происходит зимой tag наречие:достаточно{ ТИП_МОДИФ:СУЩ } tag наречие:предостаточно{ ТИП_МОДИФ:СУЩ } // В погребе форта оказалось предостаточно провизии. tag наречие:недостаточно{ ТИП_МОДИФ:СУЩ } tag наречие:немного{ ТИП_МОДИФ:СУЩ } tag наречие:немножко{ ТИП_МОДИФ:СУЩ } tag наречие:немножечко{ ТИП_МОДИФ:СУЩ } // попробуем организовать для вас немножко природы tag наречие:чуточку{ ТИП_МОДИФ:СУЩ } // дать тебе чуточку времени. tag наречие:мало{ ТИП_МОДИФ:СУЩ } tag наречие:маловато{ ТИП_МОДИФ:СУЩ } tag наречие:многовато{ ТИП_МОДИФ:СУЩ } tag наречие:немало{ ТИП_МОДИФ:СУЩ } tag наречие:чуть-чуть{ ТИП_МОДИФ:СУЩ } // Наречия типа ДАЖЕ модифицируют существительное в любом падеже: tag наречие:даже{ ТИП_МОДИФ:СУЩ2 } tag наречие:только{ ТИП_МОДИФ:СУЩ2 } tag наречие:лишь{ ТИП_МОДИФ:СУЩ2 } tag наречие:всего лишь{ ТИП_МОДИФ:СУЩ2 } tag наречие:еще{ ТИП_МОДИФ:СУЩ2 } // но прошло еще мгновение tag наречие:всего{ ТИП_МОДИФ:СУЩ2 } // мы потратили всего час // Эти наречия модифицируют предлоги: tag наречие:вслед{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // вы поехали вслед за нами tag наречие:даже{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:аж{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:только{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:только лишь{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:всего{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:всего лишь{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:почти{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // мы выследили волка уже у самой границы леса tag наречие:почти что{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:буквально{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Им предстоит дорога буквально во все регионы страны. tag наречие:уже{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:особенно{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Устали авиаторы, особенно от этой изнуряющей жары. tag наречие:именно{ ТИП_МОДИФ:ПРЕДЛ } tag наречие:исключительно{ ТИП_МОДИФ:ПРЕДЛ } tag наречие:преимущественно{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:сразу{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Сразу за домами - огороды. tag наречие:хотя бы{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Хотя бы в три? tag наречие:вплотную{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:прямо{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:впритык{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:параллельно{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:одновременно{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:невдалеке{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:вблизи{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:тайком{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:наедине{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Ей хотелось остаться наедине со своим унижением. tag наречие:слева{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:справа{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:сверху{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:снизу{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:вдали{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:недалеко{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:неподалеку{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:вместе{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:рядом{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:рядышком{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:в обнимку{ ТИП_МОДИФ:ПРЕДЛ } tag наречие:в обнимочку{ ТИП_МОДИФ:ПРЕДЛ } tag наречие:вплоть{ ТИП_МОДИФ:ПРЕДЛ } tag наречие:задолго{ ТИП_МОДИФ:ПРЕДЛ } tag наречие:незадолго{ ТИП_МОДИФ:ПРЕДЛ } tag наречие:вскоре{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:верхом{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } tag наречие:следом{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Она двинулась следом за проводником. }
Ее пронзил обжигающе ледяной клинок силы.
tag наречие:обжигающе{ ТИП_МОДИФ:ПРИЛ }
1,841,706
[ 1, 145, 248, 145, 118, 225, 145, 128, 146, 227, 145, 127, 145, 126, 145, 120, 145, 121, 145, 124, 225, 145, 127, 145, 114, 145, 119, 145, 121, 145, 116, 145, 113, 146, 241, 146, 236, 145, 118, 225, 145, 124, 145, 118, 145, 117, 146, 242, 145, 126, 145, 127, 145, 122, 225, 145, 123, 145, 124, 145, 121, 145, 126, 145, 127, 145, 123, 225, 146, 228, 145, 121, 145, 124, 146, 238, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 2692, 225, 145, 126, 145, 113, 146, 227, 145, 118, 146, 234, 145, 121, 145, 118, 30, 145, 127, 145, 114, 145, 119, 145, 121, 145, 116, 145, 113, 146, 241, 146, 236, 145, 118, 95, 225, 145, 100, 145, 251, 145, 258, 67, 145, 255, 145, 257, 145, 247, 145, 251, 145, 102, 30, 145, 258, 145, 259, 145, 251, 145, 254, 289, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-05-14 */ // File contracts/base/snx-base/interfaces/SNXRewardInterface.sol pragma solidity 0.5.16; interface SNXRewardInterface { function withdraw(uint) external; function getReward() external; function stake(uint) external; function balanceOf(address) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; } // File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.5.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); } } // File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.5.0; /** * @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; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/base/interface/IController.sol pragma solidity 0.5.16; interface IController { event SharePriceChangeLog( address indexed vault, address indexed strategy, uint256 oldSharePrice, uint256 newSharePrice, uint256 timestamp ); // [Grey list] // An EOA can safely interact with the system no matter what. // If you're using Metamask, you're using an EOA. // Only smart contracts may be affected by this grey list. // // This contract will not be able to ban any EOA from the system // even if an EOA is being added to the greyList, he/she will still be able // to interact with the whole system as if nothing happened. // Only smart contracts will be affected by being added to the greyList. // This grey list is only used in Vault.sol, see the code there for reference function greyList(address _target) external view returns(bool); function addVaultAndStrategy(address _vault, address _strategy) external; function doHardWork(address _vault) external; function hasVault(address _vault) external returns(bool); function salvage(address _token, uint256 amount) external; function salvageStrategy(address _strategy, address _token, uint256 amount) external; function notifyFee(address _underlying, uint256 fee) external; function profitSharingNumerator() external view returns (uint256); function profitSharingDenominator() external view returns (uint256); function feeRewardForwarder() external view returns(address); function setFeeRewardForwarder(address _value) external; function addHardWorker(address _worker) external; } // File contracts/base/interface/IFeeRewardForwarderV6.sol pragma solidity 0.5.16; interface IFeeRewardForwarderV6 { function poolNotifyFixedTarget(address _token, uint256 _amount) external; function notifyFeeAndBuybackAmounts(uint256 _feeAmount, address _pool, uint256 _buybackAmount) external; function notifyFeeAndBuybackAmounts(address _token, uint256 _feeAmount, address _pool, uint256 _buybackAmount) external; function profitSharingPool() external view returns (address); function configureLiquidation(address[] calldata _path, bytes32[] calldata _dexes) external; } // File contracts/base/inheritance/Storage.sol pragma solidity 0.5.16; contract Storage { address public governance; address public controller; constructor() public { governance = msg.sender; } modifier onlyGovernance() { require(isGovernance(msg.sender), "Not governance"); _; } function setGovernance(address _governance) public onlyGovernance { require(_governance != address(0), "new governance shouldn't be empty"); governance = _governance; } function setController(address _controller) public onlyGovernance { require(_controller != address(0), "new controller shouldn't be empty"); controller = _controller; } function isGovernance(address account) public view returns (bool) { return account == governance; } function isController(address account) public view returns (bool) { return account == controller; } } // File contracts/base/inheritance/Governable.sol pragma solidity 0.5.16; contract Governable { Storage public store; constructor(address _store) public { require(_store != address(0), "new storage shouldn't be empty"); store = Storage(_store); } modifier onlyGovernance() { require(store.isGovernance(msg.sender), "Not governance"); _; } function setStorage(address _store) public onlyGovernance { require(_store != address(0), "new storage shouldn't be empty"); store = Storage(_store); } function governance() public view returns (address) { return store.governance(); } } // File contracts/base/inheritance/Controllable.sol pragma solidity 0.5.16; contract Controllable is Governable { constructor(address _storage) Governable(_storage) public { } modifier onlyController() { require(store.isController(msg.sender), "Not a controller"); _; } modifier onlyControllerOrGovernance(){ require((store.isController(msg.sender) || store.isGovernance(msg.sender)), "The caller must be controller or governance"); _; } function controller() public view returns (address) { return store.controller(); } } // File contracts/base/inheritance/RewardTokenProfitNotifier.sol pragma solidity 0.5.16; contract RewardTokenProfitNotifier is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public profitSharingNumerator; uint256 public profitSharingDenominator; address public rewardToken; constructor( address _storage, address _rewardToken ) public Controllable(_storage){ rewardToken = _rewardToken; // persist in the state for immutability of the fee profitSharingNumerator = 30; //IController(controller()).profitSharingNumerator(); profitSharingDenominator = 100; //IController(controller()).profitSharingDenominator(); require(profitSharingNumerator < profitSharingDenominator, "invalid profit share"); } event ProfitLogInReward(uint256 profitAmount, uint256 feeAmount, uint256 timestamp); event ProfitAndBuybackLog(uint256 profitAmount, uint256 feeAmount, uint256 timestamp); function notifyProfitInRewardToken(uint256 _rewardBalance) internal { if( _rewardBalance > 0 ){ uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator); emit ProfitLogInReward(_rewardBalance, feeAmount, block.timestamp); IERC20(rewardToken).safeApprove(controller(), 0); IERC20(rewardToken).safeApprove(controller(), feeAmount); IController(controller()).notifyFee( rewardToken, feeAmount ); } else { emit ProfitLogInReward(0, 0, block.timestamp); } } function notifyProfitAndBuybackInRewardToken(uint256 _rewardBalance, address pool, uint256 _buybackRatio) internal { if( _rewardBalance > 0 ){ uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator); address forwarder = IController(controller()).feeRewardForwarder(); emit ProfitAndBuybackLog(_rewardBalance, feeAmount, block.timestamp); IERC20(rewardToken).safeApprove(forwarder, 0); IERC20(rewardToken).safeApprove(forwarder, _rewardBalance); IFeeRewardForwarderV6(forwarder).notifyFeeAndBuybackAmounts( rewardToken, feeAmount, pool, _rewardBalance.sub(feeAmount).mul(_buybackRatio).div(10000) ); } else { emit ProfitAndBuybackLog(0, 0, block.timestamp); } } } // File contracts/base/interface/IStrategy.sol pragma solidity 0.5.16; interface IStrategy { function unsalvagableTokens(address tokens) external view returns (bool); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function vault() external view returns (address); function withdrawAllToVault() external; function withdrawToVault(uint256 amount) external; function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch() // should only be called by controller function salvage(address recipient, address token, uint256 amount) external; function doHardWork() external; function depositArbCheck() external view returns(bool); } // File contracts/base/interface/ILiquidator.sol // SPDX-License-Identifier: MIT pragma solidity 0.5.16; interface ILiquidator { event Swap( address indexed buyToken, address indexed sellToken, address indexed target, address initiator, uint256 amountIn, uint256 slippage, uint256 total ); function swapTokenOnMultipleDEXes( uint256 amountIn, uint256 amountOutMin, address target, bytes32[] calldata dexes, address[] calldata path ) external; function swapTokenOnDEX( uint256 amountIn, uint256 amountOutMin, address target, bytes32 dexName, address[] calldata path ) external; function getAllDexes() external view returns (bytes32[] memory); } // File contracts/base/interface/ILiquidatorRegistry.sol // SPDX-License-Identifier: MIT pragma solidity 0.5.16; interface ILiquidatorRegistry { function universalLiquidator() external view returns(address); function setUniversalLiquidator(address _ul) external; function getPath( bytes32 dex, address inputToken, address outputToken ) external view returns(address[] memory); function setPath( bytes32 dex, address inputToken, address outputToken, address[] calldata path ) external; } // File contracts/base/StrategyBaseULClaimable.sol //SPDX-License-Identifier: Unlicense pragma solidity 0.5.16; contract StrategyBaseULClaimable is IStrategy, RewardTokenProfitNotifier { using SafeMath for uint256; using SafeERC20 for IERC20; event ProfitsNotCollected(address); event Liquidating(address, uint256); address public underlying; address public vault; mapping (address => bool) public unsalvagableTokens; address public universalLiquidatorRegistry; address public rewardTokenForLiquidation; bool public allowedRewardClaimable = false; address public multiSig = 0xF49440C1F012d041802b25A73e5B0B9166a75c02; modifier restricted() { require(msg.sender == vault || msg.sender == address(controller()) || msg.sender == address(governance()), "The sender has to be the controller or vault or governance"); _; } modifier onlyMultiSigOrGovernance() { require(msg.sender == multiSig || msg.sender == governance(), "The sender has to be multiSig or governance"); _; } constructor( address _storage, address _underlying, address _vault, address _rewardTokenForLiquidation, address _rewardTokenForProfitSharing, address _universalLiquidatorRegistry ) RewardTokenProfitNotifier(_storage, _rewardTokenForProfitSharing) public { rewardTokenForLiquidation = _rewardTokenForLiquidation; underlying = _underlying; vault = _vault; unsalvagableTokens[_rewardTokenForLiquidation] = true; unsalvagableTokens[_underlying] = true; universalLiquidatorRegistry = _universalLiquidatorRegistry; require(underlying != _rewardTokenForLiquidation, "reward token cannot be the same as underlying for StrategyBaseULClaimable"); } function universalLiquidator() public view returns(address) { return ILiquidatorRegistry(universalLiquidatorRegistry).universalLiquidator(); } function setMultiSig(address _address) public onlyGovernance { multiSig = _address; } // reward claiming by multiSig for some strategies function claimReward() public onlyMultiSigOrGovernance { require(allowedRewardClaimable, "reward claimable is not allowed"); _getReward(); uint256 rewardBalance = IERC20(rewardTokenForLiquidation).balanceOf(address(this)); IERC20(rewardTokenForLiquidation).safeTransfer(msg.sender, rewardBalance); } function setRewardClaimable(bool flag) public onlyGovernance { allowedRewardClaimable = flag; } function _getReward() internal { revert("Should be implemented in the derived contract"); } } // File contracts/base/interface/IVault.sol pragma solidity 0.5.16; interface IVault { function initializeVault( address _storage, address _underlying, uint256 _toInvestNumerator, uint256 _toInvestDenominator ) external ; function balanceOf(address) external view returns (uint256); function underlyingBalanceInVault() external view returns (uint256); function underlyingBalanceWithInvestment() external view returns (uint256); // function store() external view returns (address); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function strategy() external view returns (address); function setStrategy(address _strategy) external; function announceStrategyUpdate(address _strategy) external; function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external; function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdrawAll() external; function withdraw(uint256 numberOfShares) external; function getPricePerFullShare() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256); // hard work should be callable only by the controller (by the hard worker) or by governance function doHardWork() external; } // File contracts/base/interface/IRewardDistributionSwitcher.sol pragma solidity 0.5.16; contract IRewardDistributionSwitcher { function switchingAllowed(address) external returns(bool); function returnOwnership(address poolAddr) external; function enableSwitchers(address[] calldata switchers) external; function setSwithcer(address switcher, bool allowed) external; function setPoolRewardDistribution(address poolAddr, address newRewardDistributor) external; } // File contracts/base/interface/INoMintRewardPool.sol pragma solidity 0.5.16; interface INoMintRewardPool { function withdraw(uint) external; function getReward() external; function stake(uint) external; function balanceOf(address) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; function rewardDistribution() external view returns (address); function lpToken() external view returns(address); function rewardToken() external view returns(address); // only owner function setRewardDistribution(address _rewardDistributor) external; function transferOwnership(address _owner) external; function notifyRewardAmount(uint256 _reward) external; } // File contracts/base/snx-base/SNXReward2FarmStrategyUL.sol pragma solidity 0.5.16; /* * This is a general strategy for yields that are based on the synthetix reward contract * for example, yam, spaghetti, ham, shrimp. * * One strategy is deployed for one underlying asset, but the design of the contract * should allow it to switch between different reward contracts. * * It is important to note that not all SNX reward contracts that are accessible via the same interface are * suitable for this Strategy. One concrete example is CREAM.finance, as it implements a "Lock" feature and * would not allow the user to withdraw within some timeframe after the user have deposited. * This would be problematic to user as our "invest" function in the vault could be invoked by anyone anytime * and thus locking/reverting on subsequent withdrawals. Another variation is the YFI Governance: it can * activate a vote lock to stop withdrawal. * * Ref: * 1. CREAM https://etherscan.io/address/0xc29e89845fa794aa0a0b8823de23b760c3d766f5#code * 2. YAM https://etherscan.io/address/0x8538E5910c6F80419CD3170c26073Ff238048c9E#code * 3. SHRIMP https://etherscan.io/address/0x9f83883FD3cadB7d2A83a1De51F9Bf483438122e#code * 4. BASED https://etherscan.io/address/0x5BB622ba7b2F09BF23F1a9b509cd210A818c53d7#code * 5. YFII https://etherscan.io/address/0xb81D3cB2708530ea990a287142b82D058725C092#code * 6. YFIGovernance https://etherscan.io/address/0xBa37B002AbaFDd8E89a1995dA52740bbC013D992#code * * * * Respecting the current system design of choosing the best strategy under the vault, and also rewarding/funding * the public key that invokes the switch of strategies, this smart contract should be deployed twice and linked * to the same vault. When the governance want to rotate the crop, they would set the reward source on the strategy * that is not active, then set that apy higher and this one lower. * * Consequently, in the smart contract we restrict that we can only set a new reward source when it is not active. * */ contract SNXReward2FarmStrategyUL is StrategyBaseULClaimable { using SafeMath for uint256; using SafeERC20 for IERC20; address public farm; address public distributionPool; address public distributionSwitcher; address public rewardToken; bool public pausedInvesting = false; // When this flag is true, the strategy will not be able to invest. But users should be able to withdraw. SNXRewardInterface public rewardPool; // a flag for disabling selling for simplified emergency exit bool public sell = true; uint256 public sellFloor = 1; // Instead of trying to pass in the detailed liquidation path and different dexes to the liquidator, // we just pass in the input output of the liquidation path: // [ MIC, WETH, FARM ] , [SUSHI, UNI] // // This means that: // the first dex is sushi, the input is MIC and output is WETH. // the second dex is uni, the input is WETH and the output is FARM. // the universal liquidator itself would record the best path to liquidate from MIC to WETH on Sushiswap // provides the path for liquidating a token address [] public liquidationPath; // specifies which DEX is the token liquidated on bytes32 [] public liquidationDexes; event ProfitsNotCollected(); // This is only used in `investAllUnderlying()` // The user can still freely withdraw from the strategy modifier onlyNotPausedInvesting() { require(!pausedInvesting, "Action blocked as the strategy is in emergency state"); _; } modifier onlyMultiSigOrGovernance() { require(msg.sender == multiSig || msg.sender == governance(), "The sender has to be multiSig or governance"); _; } constructor( address _storage, address _underlying, address _vault, address _rewardPool, address _rewardToken, address _universalLiquidatorRegistry, address _farm, address _distributionPool ) StrategyBaseULClaimable(_storage, _underlying, _vault, _rewardToken, _farm, _universalLiquidatorRegistry) public { require(_rewardToken != _underlying, "reward token shouldn't be the same as underlying"); require(_vault == INoMintRewardPool(_distributionPool).lpToken(), "distribution pool's lp must be the vault"); require( (_farm == INoMintRewardPool(_distributionPool).rewardToken()) || (_farm == IVault(INoMintRewardPool(_distributionPool).rewardToken()).underlying()), "distribution pool's reward must be FARM or iFARM"); farm = _farm; distributionPool = _distributionPool; rewardToken = _rewardToken; rewardPool = SNXRewardInterface(_rewardPool); } function depositArbCheck() public view returns(bool) { return true; } // If there are multiple reward tokens, they should all be liquidated to // rewardToken. function _getReward() internal { if (address(rewardPool) != address(0)) { rewardPool.getReward(); } } /* * In case there are some issues discovered about the pool or underlying asset * Governance can exit the pool properly * The function is only used for emergency to exit the pool */ function emergencyExit() public onlyGovernance { rewardPool.exit(); pausedInvesting = true; } /* * Resumes the ability to invest into the underlying reward pools */ function continueInvesting() public onlyGovernance { pausedInvesting = false; } function setLiquidationPaths(address [] memory _liquidationPath, bytes32[] memory _dexes) public onlyGovernance { liquidationPath = _liquidationPath; liquidationDexes = _dexes; } function _liquidateReward() internal { uint256 rewardBalance = IERC20(rewardToken).balanceOf(address(this)); if (!sell || rewardBalance < sellFloor) { // Profits can be disabled for possible simplified and rapid exit emit ProfitsNotCollected(); return; } // sell reward token to FARM // we can accept 1 as minimum because this is called only by a trusted role address uliquidator = universalLiquidator(); IERC20(rewardToken).safeApprove(uliquidator, 0); IERC20(rewardToken).safeApprove(uliquidator, rewardBalance); ILiquidator(uliquidator).swapTokenOnMultipleDEXes( rewardBalance, 1, address(this), // target liquidationDexes, liquidationPath ); uint256 farmAmount = IERC20(farm).balanceOf(address(this)); // Share profit + buyback notifyProfitAndBuybackInRewardToken(farmAmount, distributionPool, 10000); } /* * Stakes everything the strategy holds into the reward pool */ function investAllUnderlying() internal onlyNotPausedInvesting { // this check is needed, because most of the SNX reward pools will revert if // you try to stake(0). if(IERC20(underlying).balanceOf(address(this)) > 0) { IERC20(underlying).approve(address(rewardPool), IERC20(underlying).balanceOf(address(this))); rewardPool.stake(IERC20(underlying).balanceOf(address(this))); } } /* * Withdraws all the asset to the vault */ function withdrawAllToVault() public restricted { if (address(rewardPool) != address(0)) { if (rewardPool.balanceOf(address(this)) > 0) { rewardPool.exit(); } } _liquidateReward(); if (IERC20(underlying).balanceOf(address(this)) > 0) { IERC20(underlying).safeTransfer(vault, IERC20(underlying).balanceOf(address(this))); } } /* * Withdraws all the asset to the vault */ function withdrawToVault(uint256 amount) public restricted { // Typically there wouldn't be any amount here // however, it is possible because of the emergencyExit if(amount > IERC20(underlying).balanceOf(address(this))){ // While we have the check above, we still using SafeMath below // for the peace of mind (in case something gets changed in between) uint256 needToWithdraw = amount.sub(IERC20(underlying).balanceOf(address(this))); rewardPool.withdraw(Math.min(rewardPool.balanceOf(address(this)), needToWithdraw)); } IERC20(underlying).safeTransfer(vault, amount); } /* * Note that we currently do not have a mechanism here to include the * amount of reward that is accrued. */ function investedUnderlyingBalance() external view returns (uint256) { if (address(rewardPool) == address(0)) { return IERC20(underlying).balanceOf(address(this)); } // Adding the amount locked in the reward pool and the amount that is somehow in this contract // both are in the units of "underlying" // The second part is needed because there is the emergency exit mechanism // which would break the assumption that all the funds are always inside of the reward pool return rewardPool.balanceOf(address(this)).add(IERC20(underlying).balanceOf(address(this))); } /* * Governance or Controller can claim coins that are somehow transferred into the contract * Note that they cannot come in take away coins that are used and defined in the strategy itself * Those are protected by the "unsalvagableTokens". To check, see where those are being flagged. */ function salvage(address recipient, address token, uint256 amount) external onlyControllerOrGovernance { // To make sure that governance cannot come in and take away the coins require(!unsalvagableTokens[token], "token is defined as not salvagable"); IERC20(token).safeTransfer(recipient, amount); } /* * Get the reward, sell it in exchange for underlying, invest what you got. * It's not much, but it's honest work. * * Note that although `onlyNotPausedInvesting` is not added here, * calling `investAllUnderlying()` affectively blocks the usage of `doHardWork` * when the investing is being paused by governance. */ function doHardWork() external onlyNotPausedInvesting restricted { rewardPool.getReward(); _liquidateReward(); investAllUnderlying(); } /** * Can completely disable claiming UNI rewards and selling. Good for emergency withdraw in the * simplest possible way. */ function setSell(bool s) public onlyGovernance { sell = s; } /** * Sets the minimum amount of CRV needed to trigger a sale. */ function setSellFloor(uint256 floor) public onlyGovernance { sellFloor = floor; } } // File contracts/strategies/klondike/Klondike2FarmStrategyMainnet_WBTC_KLONX.sol pragma solidity 0.5.16; contract Klondike2FarmStrategyMainnet_WBTC_KLONX is SNXReward2FarmStrategyUL { address public wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); address public wbtc_klonx = address(0x69Cda6eDa9986f7fCa8A5dBa06c819B535F4Fc50); address public klonx = address(0xbf15797BB5E47F6fB094A4abDB2cfC43F77179Ef); address public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public WBTCKLONRewardPool = address(0x185bDc02aAFbEcDc8DC574e8319228B586764415); address public constant universalLiquidatorRegistry = address(0x7882172921E99d590E097cD600554339fBDBc480); address public constant farm = address(0xa0246c9032bC3A600820415aE600c6388619A14D); constructor( address _storage, address _vault, address _distributionPool ) SNXReward2FarmStrategyUL(_storage, wbtc_klonx, _vault, WBTCKLONRewardPool, klonx, universalLiquidatorRegistry, farm, _distributionPool) public { require(IVault(_vault).underlying() == wbtc_klonx, "Underlying mismatch"); liquidationPath = [klonx, farm]; liquidationDexes.push(bytes32(uint256(keccak256("uni")))); allowedRewardClaimable = true; } }
Withdraws all the asset to the vault/
function withdrawAllToVault() public restricted { if (address(rewardPool) != address(0)) { if (rewardPool.balanceOf(address(this)) > 0) { rewardPool.exit(); } } _liquidateReward(); if (IERC20(underlying).balanceOf(address(this)) > 0) { IERC20(underlying).safeTransfer(vault, IERC20(underlying).balanceOf(address(this))); } }
2,180,212
[ 1, 1190, 9446, 87, 777, 326, 3310, 358, 326, 9229, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 598, 9446, 1595, 774, 12003, 1435, 1071, 15693, 288, 203, 565, 309, 261, 2867, 12, 266, 2913, 2864, 13, 480, 1758, 12, 20, 3719, 288, 203, 1377, 309, 261, 266, 2913, 2864, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 405, 374, 13, 288, 203, 3639, 19890, 2864, 18, 8593, 5621, 203, 1377, 289, 203, 565, 289, 203, 565, 389, 549, 26595, 340, 17631, 1060, 5621, 203, 203, 565, 309, 261, 45, 654, 39, 3462, 12, 9341, 6291, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 405, 374, 13, 288, 203, 1377, 467, 654, 39, 3462, 12, 9341, 6291, 2934, 4626, 5912, 12, 26983, 16, 467, 654, 39, 3462, 12, 9341, 6291, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xC61b9439F9C3D74011b59fe8E28cE4fffB41D3B5/sources/InvestementBeta.sol
* @dev Setter functions ./
function setAdmin(address _admin) external onlyOwner { require( _admin != address(0), "Formation.Fi: zero address" ); admin = Admin(_admin); }
3,702,227
[ 1, 8465, 4186, 263, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 4446, 12, 2867, 389, 3666, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 389, 3666, 480, 1758, 12, 20, 3631, 203, 5411, 315, 12624, 18, 42, 77, 30, 3634, 1758, 6, 203, 3639, 11272, 203, 540, 203, 3639, 3981, 273, 7807, 24899, 3666, 1769, 203, 565, 289, 7010, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; import {IERC20} from "./IERC20.sol"; interface IERC20Detailed is IERC20 { function name() external view returns(string memory); function symbol() external view returns(string memory); function decimals() external view returns(uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; interface ITransferHook { function onTransfer(address from, address to, uint256 amount) external; } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override virtual { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } pragma solidity ^0.6.0; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } pragma solidity ^0.6.0; import './Proxy.sol'; import './Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } pragma solidity ^0.6.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./Context.sol"; import "../interfaces/IERC20.sol"; import "./SafeMath.sol"; import "./Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string internal _name; string internal _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.10; import "./BaseAdminUpgradeabilityProxy.sol"; import "./InitializableUpgradeabilityProxy.sol"; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(_admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.10; import "./BaseUpgradeabilityProxy.sol"; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; import {ERC20} from "../open-zeppelin/ERC20.sol"; import {ITransferHook} from "../interfaces/ITransferHook.sol"; import {VersionedInitializable} from "../utils/VersionedInitializable.sol"; /** * @notice implementation of the AAVE token contract * @author Aave */ contract AaveToken is ERC20, VersionedInitializable { /// @dev snapshot of a value on a specific block, used for balances struct Snapshot { uint128 blockNumber; uint128 value; } string internal constant NAME = "Aave Token"; string internal constant SYMBOL = "AAVE"; uint8 internal constant DECIMALS = 18; /// @dev the amount being distributed for the LEND -> AAVE migration uint256 internal constant MIGRATION_AMOUNT = 13000000 ether; /// @dev the amount being distributed for the PSI and PEI uint256 internal constant DISTRIBUTION_AMOUNT = 3000000 ether; uint256 public constant REVISION = 1; /// @dev owner => next valid nonce to submit with permit() mapping (address => uint256) public _nonces; mapping (address => mapping (uint256 => Snapshot)) public _snapshots; mapping (address => uint256) public _countsSnapshots; /// @dev reference to the Aave governance contract to call (if initialized) on _beforeTokenTransfer /// !!! IMPORTANT The Aave governance is considered a trustable contract, being its responsibility /// to control all potential reentrancies by calling back the AaveToken ITransferHook public _aaveGovernance; bytes32 public DOMAIN_SEPARATOR; bytes public constant EIP712_REVISION = bytes("1"); bytes32 internal constant EIP712_DOMAIN = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); event SnapshotDone(address owner, uint128 oldValue, uint128 newValue); constructor() ERC20(NAME, SYMBOL) public {} /** * @dev initializes the contract upon assignment to the InitializableAdminUpgradeabilityProxy * @param migrator the address of the LEND -> AAVE migration contract * @param distributor the address of the AAVE distribution contract */ function initialize( address migrator, address distributor, ITransferHook aaveGovernance ) external initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712_DOMAIN, keccak256(bytes(NAME)), keccak256(EIP712_REVISION), chainId, address(this) )); _name = NAME; _symbol = SYMBOL; _setupDecimals(DECIMALS); _aaveGovernance = aaveGovernance; _mint(migrator, MIGRATION_AMOUNT); _mint(distributor, DISTRIBUTION_AMOUNT); } /** * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner the owner of the funds * @param spender the spender * @param value the amount * @param deadline the deadline timestamp, type(uint256).max for no deadline * @param v signature param * @param s signature param * @param r signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), "INVALID_OWNER"); //solium-disable-next-line require(block.timestamp <= deadline, "INVALID_EXPIRATION"); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require(owner == ecrecover(digest, v, r, s), "INVALID_SIGNATURE"); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @dev returns the revision of the implementation contract */ function getRevision() internal pure override returns (uint256) { return REVISION; } /** * @dev Writes a snapshot for an owner of tokens * @param owner The owner of the tokens * @param oldValue The value before the operation that is gonna be executed after the snapshot * @param newValue The value after the operation */ function _writeSnapshot(address owner, uint128 oldValue, uint128 newValue) internal { uint128 currentBlock = uint128(block.number); uint256 ownerCountOfSnapshots = _countsSnapshots[owner]; mapping (uint256 => Snapshot) storage snapshotsOwner = _snapshots[owner]; // Doing multiple operations in the same block if (ownerCountOfSnapshots != 0 && snapshotsOwner[ownerCountOfSnapshots.sub(1)].blockNumber == currentBlock) { snapshotsOwner[ownerCountOfSnapshots.sub(1)].value = newValue; } else { snapshotsOwner[ownerCountOfSnapshots] = Snapshot(currentBlock, newValue); _countsSnapshots[owner] = ownerCountOfSnapshots.add(1); } emit SnapshotDone(owner, oldValue, newValue); } /** * @dev Writes a snapshot before any operation involving transfer of value: _transfer, _mint and _burn * - On _transfer, it writes snapshots for both "from" and "to" * - On _mint, only for _to * - On _burn, only for _from * @param from the from address * @param to the to address * @param amount the amount to transfer */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { if (from == to) { return; } if (from != address(0)) { uint256 fromBalance = balanceOf(from); _writeSnapshot(from, uint128(fromBalance), uint128(fromBalance.sub(amount))); } if (to != address(0)) { uint256 toBalance = balanceOf(to); _writeSnapshot(to, uint128(toBalance), uint128(toBalance.add(amount))); } // caching the aave governance address to avoid multiple state loads ITransferHook aaveGovernance = _aaveGovernance; if (aaveGovernance != ITransferHook(0)) { aaveGovernance.onTransfer(from, to, amount); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; /** * @title VersionedInitializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; import {IERC20} from "../interfaces/IERC20.sol"; import {SafeMath} from "../open-zeppelin/SafeMath.sol"; import {VersionedInitializable} from "../utils/VersionedInitializable.sol"; /** * @title LendToAaveMigrator * @notice This contract implements the migration from LEND to AAVE token * @author Aave */ contract LendToAaveMigrator is VersionedInitializable { using SafeMath for uint256; IERC20 public immutable AAVE; IERC20 public immutable LEND; uint256 public immutable LEND_AAVE_RATIO; uint256 public constant REVISION = 1; uint256 public _totalLendMigrated; /** * @dev emitted on migration * @param sender the caller of the migration * @param amount the amount being migrated */ event LendMigrated(address indexed sender, uint256 indexed amount); /** * @param aave the address of the AAVE token * @param lend the address of the LEND token * @param lendAaveRatio the exchange rate between LEND and AAVE */ constructor(IERC20 aave, IERC20 lend, uint256 lendAaveRatio) public { AAVE = aave; LEND = lend; LEND_AAVE_RATIO = lendAaveRatio; } /** * @dev initializes the implementation */ function initialize() public initializer { } /** * @dev returns true if the migration started */ function migrationStarted() external view returns(bool) { return lastInitializedRevision != 0; } /** * @dev executes the migration from LEND to AAVE. Users need to give allowance to this contract to transfer LEND before executing * this transaction. * @param amount the amount of LEND to be migrated */ function migrateFromLEND(uint256 amount) external { require(lastInitializedRevision != 0, "MIGRATION_NOT_STARTED"); _totalLendMigrated = _totalLendMigrated.add(amount); LEND.transferFrom(msg.sender, address(this), amount); AAVE.transfer(msg.sender, amount.div(LEND_AAVE_RATIO)); emit LendMigrated(msg.sender, amount); } /** * @dev returns the implementation revision * @return the implementation revision */ function getRevision() internal pure override returns (uint256) { return REVISION; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; import "../interfaces/IERC20.sol"; contract DoubleTransferHelper { IERC20 public immutable AAVE; constructor(IERC20 aave) public { AAVE = aave; } function doubleSend(address to, uint256 amount1, uint256 amount2) external { AAVE.transfer(to, amount1); AAVE.transfer(to, amount2); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; import "../open-zeppelin/ERC20.sol"; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableErc20 is ERC20 { constructor(string memory name, string memory symbol, uint8 decimals) ERC20(name, symbol) public { _setupDecimals(decimals); } /** * @dev Function to mint tokens * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(msg.sender, value); return true; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.10; import {ITransferHook} from "../interfaces/ITransferHook.sol"; contract MockTransferHook is ITransferHook { event MockHookEvent(); function onTransfer(address from, address to, uint256 amount) external override { emit MockHookEvent(); } }
* @title Proxy @dev Implements delegation of calls to other contracts, with proper forwarding of return values and bubbling of failures. It defines a fallback function that delegates all calls to the address returned by the abstract _implementation() internal function./
abstract contract Proxy { fallback () payable external { _fallback(); } function _implementation() internal virtual view returns (address); function _delegate(address implementation) internal { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result } } function _implementation() internal virtual view returns (address); function _delegate(address implementation) internal { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result } } case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } function _willFallback() internal virtual { } function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
12,879,719
[ 1, 3886, 225, 29704, 23595, 434, 4097, 358, 1308, 20092, 16, 598, 5338, 20635, 434, 327, 924, 471, 324, 22298, 2456, 434, 11720, 18, 2597, 11164, 279, 5922, 445, 716, 22310, 777, 4097, 358, 326, 1758, 2106, 635, 326, 8770, 389, 30810, 1435, 2713, 445, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 7659, 288, 203, 225, 5922, 1832, 8843, 429, 3903, 288, 203, 565, 389, 16471, 5621, 203, 225, 289, 203, 203, 225, 445, 389, 30810, 1435, 2713, 5024, 1476, 1135, 261, 2867, 1769, 203, 203, 225, 445, 389, 22216, 12, 2867, 4471, 13, 2713, 288, 203, 565, 19931, 288, 203, 1377, 745, 892, 3530, 12, 20, 16, 374, 16, 745, 13178, 554, 10756, 203, 203, 1377, 2231, 563, 519, 7152, 1991, 12, 31604, 9334, 4471, 16, 374, 16, 745, 13178, 554, 9334, 374, 16, 374, 13, 203, 203, 1377, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 10756, 203, 203, 1377, 1620, 563, 203, 565, 289, 203, 225, 289, 203, 203, 225, 445, 389, 30810, 1435, 2713, 5024, 1476, 1135, 261, 2867, 1769, 203, 203, 225, 445, 389, 22216, 12, 2867, 4471, 13, 2713, 288, 203, 565, 19931, 288, 203, 1377, 745, 892, 3530, 12, 20, 16, 374, 16, 745, 13178, 554, 10756, 203, 203, 1377, 2231, 563, 519, 7152, 1991, 12, 31604, 9334, 4471, 16, 374, 16, 745, 13178, 554, 9334, 374, 16, 374, 13, 203, 203, 1377, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 10756, 203, 203, 1377, 1620, 563, 203, 565, 289, 203, 225, 289, 203, 203, 1377, 648, 374, 288, 15226, 12, 20, 16, 327, 13178, 554, 10756, 289, 203, 1377, 805, 288, 327, 12, 20, 16, 327, 13178, 554, 10756, 289, 203, 225, 445, 389, 20194, 12355, 1435, 2713, 5024, 288, 203, 225, 289, 203, 203, 225, 445, 389, 16471, 1435, 2 ]
pragma solidity >=0.4.24 <0.6.0; // This test demonstrates that solc.exe detects // inconsistencies in chained constructors' arguments // This test results in solc error: see lines 13 and 21 // compare with ConstructorLinearizedWithArgs.sol, which compiles contract A { uint a; constructor (uint x) public { a = x; } } contract B is A { uint b; constructor (uint x) A(x+1) public { //solc error: "Base constructor arguments given twice" (for A) b = x + 1; assert(a == x + 1); } } contract C is A { uint c; constructor (uint x) A(x+1) public { //solc error: "Base constructor arguments given twice" (for A) c = x + 2; assert(a == x + 2); } } contract D is B, C { uint d; constructor (uint x) B(x+3) C(x+4) public { d = x + 3; //assert (a == x + 4); //after calling B(x+3) //assert (b == x + 4); //after calling B(x+3) assert(a == x + 6); // after calling C(x+4) assert (c == x + 6); // after calling C(x+4) } }
solc error: "Base constructor arguments given twice" (for A)
constructor (uint x) A(x+1) public {
12,924,496
[ 1, 18281, 71, 555, 30, 315, 2171, 3885, 1775, 864, 13605, 6, 261, 1884, 432, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 261, 11890, 619, 13, 432, 12, 92, 15, 21, 13, 1071, 288, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0xC033758880a5e0ec71A4015674344e25B8D44b1f/sources/project:/contracts/TribotStakingV2.sol
Initialize the contract
contract TribotStakingV2 is Initializable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; IERC20MetadataUpgradeable public token; uint256 public totalStaked; uint256 public minDeposit; uint256 public timeStep; uint256 public percentDivider; uint256 public basePercent; uint256 public uniqueStakers; pragma solidity ^0.8.18; function initialize(IERC20MetadataUpgradeable _token) external initializer { __Ownable_init(); token = _token; minDeposit = 100 * 10 ** token.decimals(); timeStep = 14 days; percentDivider = 100_00; basePercent = 10; } struct User { uint256 amount; uint256 checkpoint; uint256 claimedReward; uint256 totalclaimed; uint256 reward; uint256 startTime; uint256 withdrawTime; bool isActive; bool isExists; } mapping(address => User) public users; mapping(address => mapping(address => uint256)) public userLastPoolCount; mapping(address => mapping(address => uint256)) public prevRemainingReward; address public usdtStaking; event STAKE(address Staker, uint256 amount); event CLAIM(address Staker, uint256 amount); event WITHDRAW(address Staker, uint256 amount); mapping(address => mapping(uint256 => uint256)) public rewardStakeHistory; IRewardManager public rewardManager; function stake(uint256 _amount) public { User storage user = users[msg.sender]; require(_amount >= minDeposit, "Amount less than min amount"); if (!user.isExists) { user.isExists = true; uniqueStakers++; user.startTime = block.timestamp; uint256 claimableReward = calculateReward(msg.sender); if (claimableReward > 0) { token.transfer(msg.sender, claimableReward); } address[] memory tokens, uint256[] memory balances ) = calculatePoolReward(msg.sender); uint256 rewardSent; for (uint256 i; i < tokens.length; i++) { uint256 poolRewardAmount = balances[i]; address rewardToken = tokens[i]; prevRemainingReward[msg.sender][tokens[i]] = 0; if (poolRewardAmount != 0) { rewardSent++; rewardManager.withdrawRewardTokens( rewardToken, msg.sender, poolRewardAmount ); } } updateLastClaimedIndex(msg.sender); } token.transferFrom(msg.sender, address(this), _amount); user.amount += _amount; user.claimedReward = 0; user.reward = user.amount.mul(basePercent).div(percentDivider); totalStaked += _amount; user.checkpoint = block.timestamp; user.withdrawTime = block.timestamp + timeStep; user.isActive = true; emit STAKE(msg.sender, _amount); } function stake(uint256 _amount) public { User storage user = users[msg.sender]; require(_amount >= minDeposit, "Amount less than min amount"); if (!user.isExists) { user.isExists = true; uniqueStakers++; user.startTime = block.timestamp; uint256 claimableReward = calculateReward(msg.sender); if (claimableReward > 0) { token.transfer(msg.sender, claimableReward); } address[] memory tokens, uint256[] memory balances ) = calculatePoolReward(msg.sender); uint256 rewardSent; for (uint256 i; i < tokens.length; i++) { uint256 poolRewardAmount = balances[i]; address rewardToken = tokens[i]; prevRemainingReward[msg.sender][tokens[i]] = 0; if (poolRewardAmount != 0) { rewardSent++; rewardManager.withdrawRewardTokens( rewardToken, msg.sender, poolRewardAmount ); } } updateLastClaimedIndex(msg.sender); } token.transferFrom(msg.sender, address(this), _amount); user.amount += _amount; user.claimedReward = 0; user.reward = user.amount.mul(basePercent).div(percentDivider); totalStaked += _amount; user.checkpoint = block.timestamp; user.withdrawTime = block.timestamp + timeStep; user.isActive = true; emit STAKE(msg.sender, _amount); } } else { function stake(uint256 _amount) public { User storage user = users[msg.sender]; require(_amount >= minDeposit, "Amount less than min amount"); if (!user.isExists) { user.isExists = true; uniqueStakers++; user.startTime = block.timestamp; uint256 claimableReward = calculateReward(msg.sender); if (claimableReward > 0) { token.transfer(msg.sender, claimableReward); } address[] memory tokens, uint256[] memory balances ) = calculatePoolReward(msg.sender); uint256 rewardSent; for (uint256 i; i < tokens.length; i++) { uint256 poolRewardAmount = balances[i]; address rewardToken = tokens[i]; prevRemainingReward[msg.sender][tokens[i]] = 0; if (poolRewardAmount != 0) { rewardSent++; rewardManager.withdrawRewardTokens( rewardToken, msg.sender, poolRewardAmount ); } } updateLastClaimedIndex(msg.sender); } token.transferFrom(msg.sender, address(this), _amount); user.amount += _amount; user.claimedReward = 0; user.reward = user.amount.mul(basePercent).div(percentDivider); totalStaked += _amount; user.checkpoint = block.timestamp; user.withdrawTime = block.timestamp + timeStep; user.isActive = true; emit STAKE(msg.sender, _amount); } ( function stake(uint256 _amount) public { User storage user = users[msg.sender]; require(_amount >= minDeposit, "Amount less than min amount"); if (!user.isExists) { user.isExists = true; uniqueStakers++; user.startTime = block.timestamp; uint256 claimableReward = calculateReward(msg.sender); if (claimableReward > 0) { token.transfer(msg.sender, claimableReward); } address[] memory tokens, uint256[] memory balances ) = calculatePoolReward(msg.sender); uint256 rewardSent; for (uint256 i; i < tokens.length; i++) { uint256 poolRewardAmount = balances[i]; address rewardToken = tokens[i]; prevRemainingReward[msg.sender][tokens[i]] = 0; if (poolRewardAmount != 0) { rewardSent++; rewardManager.withdrawRewardTokens( rewardToken, msg.sender, poolRewardAmount ); } } updateLastClaimedIndex(msg.sender); } token.transferFrom(msg.sender, address(this), _amount); user.amount += _amount; user.claimedReward = 0; user.reward = user.amount.mul(basePercent).div(percentDivider); totalStaked += _amount; user.checkpoint = block.timestamp; user.withdrawTime = block.timestamp + timeStep; user.isActive = true; emit STAKE(msg.sender, _amount); } function stake(uint256 _amount) public { User storage user = users[msg.sender]; require(_amount >= minDeposit, "Amount less than min amount"); if (!user.isExists) { user.isExists = true; uniqueStakers++; user.startTime = block.timestamp; uint256 claimableReward = calculateReward(msg.sender); if (claimableReward > 0) { token.transfer(msg.sender, claimableReward); } address[] memory tokens, uint256[] memory balances ) = calculatePoolReward(msg.sender); uint256 rewardSent; for (uint256 i; i < tokens.length; i++) { uint256 poolRewardAmount = balances[i]; address rewardToken = tokens[i]; prevRemainingReward[msg.sender][tokens[i]] = 0; if (poolRewardAmount != 0) { rewardSent++; rewardManager.withdrawRewardTokens( rewardToken, msg.sender, poolRewardAmount ); } } updateLastClaimedIndex(msg.sender); } token.transferFrom(msg.sender, address(this), _amount); user.amount += _amount; user.claimedReward = 0; user.reward = user.amount.mul(basePercent).div(percentDivider); totalStaked += _amount; user.checkpoint = block.timestamp; user.withdrawTime = block.timestamp + timeStep; user.isActive = true; emit STAKE(msg.sender, _amount); } function claim() public { User storage user = users[msg.sender]; require(user.isActive, "Already withdrawn"); uint256 rewardAmount; rewardAmount = calculateReward(msg.sender); require(rewardAmount > 0, "Can't claim 0"); token.transfer(msg.sender, rewardAmount); ( address[] memory tokens, uint256[] memory balances ) = calculatePoolReward(msg.sender); uint256 rewardSent; for (uint256 i; i < tokens.length; i++) { uint256 poolRewardAmount = balances[i]; address rewardToken = tokens[i]; prevRemainingReward[msg.sender][tokens[i]] = 0; if (poolRewardAmount != 0) { rewardSent++; rewardManager.withdrawRewardTokens( rewardToken, msg.sender, poolRewardAmount ); } } user.checkpoint = block.timestamp; user.claimedReward += rewardAmount; user.totalclaimed += rewardAmount; updateLastClaimedIndex(msg.sender); emit CLAIM(msg.sender, rewardAmount); } function claim() public { User storage user = users[msg.sender]; require(user.isActive, "Already withdrawn"); uint256 rewardAmount; rewardAmount = calculateReward(msg.sender); require(rewardAmount > 0, "Can't claim 0"); token.transfer(msg.sender, rewardAmount); ( address[] memory tokens, uint256[] memory balances ) = calculatePoolReward(msg.sender); uint256 rewardSent; for (uint256 i; i < tokens.length; i++) { uint256 poolRewardAmount = balances[i]; address rewardToken = tokens[i]; prevRemainingReward[msg.sender][tokens[i]] = 0; if (poolRewardAmount != 0) { rewardSent++; rewardManager.withdrawRewardTokens( rewardToken, msg.sender, poolRewardAmount ); } } user.checkpoint = block.timestamp; user.claimedReward += rewardAmount; user.totalclaimed += rewardAmount; updateLastClaimedIndex(msg.sender); emit CLAIM(msg.sender, rewardAmount); } function claim() public { User storage user = users[msg.sender]; require(user.isActive, "Already withdrawn"); uint256 rewardAmount; rewardAmount = calculateReward(msg.sender); require(rewardAmount > 0, "Can't claim 0"); token.transfer(msg.sender, rewardAmount); ( address[] memory tokens, uint256[] memory balances ) = calculatePoolReward(msg.sender); uint256 rewardSent; for (uint256 i; i < tokens.length; i++) { uint256 poolRewardAmount = balances[i]; address rewardToken = tokens[i]; prevRemainingReward[msg.sender][tokens[i]] = 0; if (poolRewardAmount != 0) { rewardSent++; rewardManager.withdrawRewardTokens( rewardToken, msg.sender, poolRewardAmount ); } } user.checkpoint = block.timestamp; user.claimedReward += rewardAmount; user.totalclaimed += rewardAmount; updateLastClaimedIndex(msg.sender); emit CLAIM(msg.sender, rewardAmount); } function restake() public { require(false, "Not implemented"); User storage user = users[msg.sender]; uint256 claimableReward = calculateReward(msg.sender); require(claimableReward > 0, "Nothing to restake"); user.claimedReward = 0; user.totalclaimed += claimableReward; user.amount += claimableReward; user.checkpoint = block.timestamp; user.reward = user.amount.mul(basePercent).div(percentDivider); user.withdrawTime = block.timestamp + timeStep; totalStaked += claimableReward; } function calculateReward(address _user) public view returns (uint256) { User storage user = users[_user]; uint256 _reward; uint256 rewardDuration = block.timestamp.sub(user.checkpoint); _reward = user.amount.mul(rewardDuration).mul(basePercent).div( percentDivider.mul(timeStep) ); if (_reward.add(user.claimedReward) > user.reward) { _reward = user.reward.sub(user.claimedReward); } return _reward; } function calculateReward(address _user) public view returns (uint256) { User storage user = users[_user]; uint256 _reward; uint256 rewardDuration = block.timestamp.sub(user.checkpoint); _reward = user.amount.mul(rewardDuration).mul(basePercent).div( percentDivider.mul(timeStep) ); if (_reward.add(user.claimedReward) > user.reward) { _reward = user.reward.sub(user.claimedReward); } return _reward; } function withdraw() public { User storage user = users[msg.sender]; require(user.isActive, "user is not active!"); require(block.timestamp > user.withdrawTime, "Wait for withdraw time!"); uint256 stakedAmount = user.amount; uint256 claimAbleReward = calculateReward(msg.sender); user.amount = 0; user.reward = 0; user.claimedReward = 0; user.totalclaimed = claimAbleReward; user.isActive = false; token.transfer(msg.sender, stakedAmount); totalStaked -= stakedAmount; if (claimAbleReward > 0) { claim(); } } function withdraw() public { User storage user = users[msg.sender]; require(user.isActive, "user is not active!"); require(block.timestamp > user.withdrawTime, "Wait for withdraw time!"); uint256 stakedAmount = user.amount; uint256 claimAbleReward = calculateReward(msg.sender); user.amount = 0; user.reward = 0; user.claimedReward = 0; user.totalclaimed = claimAbleReward; user.isActive = false; token.transfer(msg.sender, stakedAmount); totalStaked -= stakedAmount; if (claimAbleReward > 0) { claim(); } } function calculatePoolReward( address _user ) public view returns (address[] memory, uint256[] memory) { User storage user = users[_user]; uint256 _tokensCount = rewardManager.totalTokens(); address[] memory tokens = new address[](_tokensCount); uint256[] memory balances = new uint256[](_tokensCount); uint256 stakedAmount = user.amount; uint256 _tokenIndex = 0; for (uint256 j = 0; j < _tokensCount; j++) { address rewardToken = rewardManager.rewardToken(j); if (rewardManager.isRewardToken(rewardToken)) { uint256 totalAddedRewardCount = rewardManager.totalRewardCount( rewardToken ); uint256 lastUserClaimed = userLastPoolCount[_user][rewardToken]; for ( uint256 k = lastUserClaimed + 1; k <= totalAddedRewardCount; k++ ) { uint256 totalAddedReward = getCurrentShareAmount( _user, stakedAmount, rewardToken, k ); uint256 stakedAmountAt = rewardStakeHistory[rewardToken][k]; uint256 _claimableReward; if (stakedAmountAt != 0) { uint256 currentPercentage = stakedAmount .mul(percentDivider) .div(stakedAmountAt); _claimableReward = totalAddedReward .mul(currentPercentage) .div(percentDivider); } balances[_tokenIndex] += _claimableReward; } balances[_tokenIndex] += prevRemainingReward[_user][ rewardToken ]; if (tokens[_tokenIndex] == address(0)) { tokens[_tokenIndex] = rewardToken; } _tokenIndex++; } } return (tokens, balances); } function calculatePoolReward( address _user ) public view returns (address[] memory, uint256[] memory) { User storage user = users[_user]; uint256 _tokensCount = rewardManager.totalTokens(); address[] memory tokens = new address[](_tokensCount); uint256[] memory balances = new uint256[](_tokensCount); uint256 stakedAmount = user.amount; uint256 _tokenIndex = 0; for (uint256 j = 0; j < _tokensCount; j++) { address rewardToken = rewardManager.rewardToken(j); if (rewardManager.isRewardToken(rewardToken)) { uint256 totalAddedRewardCount = rewardManager.totalRewardCount( rewardToken ); uint256 lastUserClaimed = userLastPoolCount[_user][rewardToken]; for ( uint256 k = lastUserClaimed + 1; k <= totalAddedRewardCount; k++ ) { uint256 totalAddedReward = getCurrentShareAmount( _user, stakedAmount, rewardToken, k ); uint256 stakedAmountAt = rewardStakeHistory[rewardToken][k]; uint256 _claimableReward; if (stakedAmountAt != 0) { uint256 currentPercentage = stakedAmount .mul(percentDivider) .div(stakedAmountAt); _claimableReward = totalAddedReward .mul(currentPercentage) .div(percentDivider); } balances[_tokenIndex] += _claimableReward; } balances[_tokenIndex] += prevRemainingReward[_user][ rewardToken ]; if (tokens[_tokenIndex] == address(0)) { tokens[_tokenIndex] = rewardToken; } _tokenIndex++; } } return (tokens, balances); } function calculatePoolReward( address _user ) public view returns (address[] memory, uint256[] memory) { User storage user = users[_user]; uint256 _tokensCount = rewardManager.totalTokens(); address[] memory tokens = new address[](_tokensCount); uint256[] memory balances = new uint256[](_tokensCount); uint256 stakedAmount = user.amount; uint256 _tokenIndex = 0; for (uint256 j = 0; j < _tokensCount; j++) { address rewardToken = rewardManager.rewardToken(j); if (rewardManager.isRewardToken(rewardToken)) { uint256 totalAddedRewardCount = rewardManager.totalRewardCount( rewardToken ); uint256 lastUserClaimed = userLastPoolCount[_user][rewardToken]; for ( uint256 k = lastUserClaimed + 1; k <= totalAddedRewardCount; k++ ) { uint256 totalAddedReward = getCurrentShareAmount( _user, stakedAmount, rewardToken, k ); uint256 stakedAmountAt = rewardStakeHistory[rewardToken][k]; uint256 _claimableReward; if (stakedAmountAt != 0) { uint256 currentPercentage = stakedAmount .mul(percentDivider) .div(stakedAmountAt); _claimableReward = totalAddedReward .mul(currentPercentage) .div(percentDivider); } balances[_tokenIndex] += _claimableReward; } balances[_tokenIndex] += prevRemainingReward[_user][ rewardToken ]; if (tokens[_tokenIndex] == address(0)) { tokens[_tokenIndex] = rewardToken; } _tokenIndex++; } } return (tokens, balances); } function calculatePoolReward( address _user ) public view returns (address[] memory, uint256[] memory) { User storage user = users[_user]; uint256 _tokensCount = rewardManager.totalTokens(); address[] memory tokens = new address[](_tokensCount); uint256[] memory balances = new uint256[](_tokensCount); uint256 stakedAmount = user.amount; uint256 _tokenIndex = 0; for (uint256 j = 0; j < _tokensCount; j++) { address rewardToken = rewardManager.rewardToken(j); if (rewardManager.isRewardToken(rewardToken)) { uint256 totalAddedRewardCount = rewardManager.totalRewardCount( rewardToken ); uint256 lastUserClaimed = userLastPoolCount[_user][rewardToken]; for ( uint256 k = lastUserClaimed + 1; k <= totalAddedRewardCount; k++ ) { uint256 totalAddedReward = getCurrentShareAmount( _user, stakedAmount, rewardToken, k ); uint256 stakedAmountAt = rewardStakeHistory[rewardToken][k]; uint256 _claimableReward; if (stakedAmountAt != 0) { uint256 currentPercentage = stakedAmount .mul(percentDivider) .div(stakedAmountAt); _claimableReward = totalAddedReward .mul(currentPercentage) .div(percentDivider); } balances[_tokenIndex] += _claimableReward; } balances[_tokenIndex] += prevRemainingReward[_user][ rewardToken ]; if (tokens[_tokenIndex] == address(0)) { tokens[_tokenIndex] = rewardToken; } _tokenIndex++; } } return (tokens, balances); } function calculatePoolReward( address _user ) public view returns (address[] memory, uint256[] memory) { User storage user = users[_user]; uint256 _tokensCount = rewardManager.totalTokens(); address[] memory tokens = new address[](_tokensCount); uint256[] memory balances = new uint256[](_tokensCount); uint256 stakedAmount = user.amount; uint256 _tokenIndex = 0; for (uint256 j = 0; j < _tokensCount; j++) { address rewardToken = rewardManager.rewardToken(j); if (rewardManager.isRewardToken(rewardToken)) { uint256 totalAddedRewardCount = rewardManager.totalRewardCount( rewardToken ); uint256 lastUserClaimed = userLastPoolCount[_user][rewardToken]; for ( uint256 k = lastUserClaimed + 1; k <= totalAddedRewardCount; k++ ) { uint256 totalAddedReward = getCurrentShareAmount( _user, stakedAmount, rewardToken, k ); uint256 stakedAmountAt = rewardStakeHistory[rewardToken][k]; uint256 _claimableReward; if (stakedAmountAt != 0) { uint256 currentPercentage = stakedAmount .mul(percentDivider) .div(stakedAmountAt); _claimableReward = totalAddedReward .mul(currentPercentage) .div(percentDivider); } balances[_tokenIndex] += _claimableReward; } balances[_tokenIndex] += prevRemainingReward[_user][ rewardToken ]; if (tokens[_tokenIndex] == address(0)) { tokens[_tokenIndex] = rewardToken; } _tokenIndex++; } } return (tokens, balances); } function calculatePoolReward( address _user ) public view returns (address[] memory, uint256[] memory) { User storage user = users[_user]; uint256 _tokensCount = rewardManager.totalTokens(); address[] memory tokens = new address[](_tokensCount); uint256[] memory balances = new uint256[](_tokensCount); uint256 stakedAmount = user.amount; uint256 _tokenIndex = 0; for (uint256 j = 0; j < _tokensCount; j++) { address rewardToken = rewardManager.rewardToken(j); if (rewardManager.isRewardToken(rewardToken)) { uint256 totalAddedRewardCount = rewardManager.totalRewardCount( rewardToken ); uint256 lastUserClaimed = userLastPoolCount[_user][rewardToken]; for ( uint256 k = lastUserClaimed + 1; k <= totalAddedRewardCount; k++ ) { uint256 totalAddedReward = getCurrentShareAmount( _user, stakedAmount, rewardToken, k ); uint256 stakedAmountAt = rewardStakeHistory[rewardToken][k]; uint256 _claimableReward; if (stakedAmountAt != 0) { uint256 currentPercentage = stakedAmount .mul(percentDivider) .div(stakedAmountAt); _claimableReward = totalAddedReward .mul(currentPercentage) .div(percentDivider); } balances[_tokenIndex] += _claimableReward; } balances[_tokenIndex] += prevRemainingReward[_user][ rewardToken ]; if (tokens[_tokenIndex] == address(0)) { tokens[_tokenIndex] = rewardToken; } _tokenIndex++; } } return (tokens, balances); } function getCurrentShareAmount( address _user, uint256 _stakedAmount, address rewardToken, uint256 k ) public view returns (uint256) { if (_stakedAmount == 0) { return 0; } (uint256 usdtStaked, , ) = IStaking(usdtStaking) .calculateTotalStakedInfo(_user); uint256 totalAddedReward; if (usdtStaked != 0) { totalAddedReward = rewardManager.totalRewardSharePlus(rewardToken, k) / 2; totalAddedReward = rewardManager.totalRewardShareTribot( rewardToken, k ); } return totalAddedReward == 0 ? rewardManager.totalAddedRewards(rewardToken, k) : totalAddedReward; } function getCurrentShareAmount( address _user, uint256 _stakedAmount, address rewardToken, uint256 k ) public view returns (uint256) { if (_stakedAmount == 0) { return 0; } (uint256 usdtStaked, , ) = IStaking(usdtStaking) .calculateTotalStakedInfo(_user); uint256 totalAddedReward; if (usdtStaked != 0) { totalAddedReward = rewardManager.totalRewardSharePlus(rewardToken, k) / 2; totalAddedReward = rewardManager.totalRewardShareTribot( rewardToken, k ); } return totalAddedReward == 0 ? rewardManager.totalAddedRewards(rewardToken, k) : totalAddedReward; } function getCurrentShareAmount( address _user, uint256 _stakedAmount, address rewardToken, uint256 k ) public view returns (uint256) { if (_stakedAmount == 0) { return 0; } (uint256 usdtStaked, , ) = IStaking(usdtStaking) .calculateTotalStakedInfo(_user); uint256 totalAddedReward; if (usdtStaked != 0) { totalAddedReward = rewardManager.totalRewardSharePlus(rewardToken, k) / 2; totalAddedReward = rewardManager.totalRewardShareTribot( rewardToken, k ); } return totalAddedReward == 0 ? rewardManager.totalAddedRewards(rewardToken, k) : totalAddedReward; } } else { function updateLastClaimedIndex(address _user) internal { uint256 _tokensCount = rewardManager.totalTokens(); for (uint256 j = 0; j < _tokensCount; j++) { address rewardToken = rewardManager.rewardToken(j); userLastPoolCount[_user][rewardToken] = rewardManager .totalRewardCount(rewardToken); } } function updateLastClaimedIndex(address _user) internal { uint256 _tokensCount = rewardManager.totalTokens(); for (uint256 j = 0; j < _tokensCount; j++) { address rewardToken = rewardManager.rewardToken(j); userLastPoolCount[_user][rewardToken] = rewardManager .totalRewardCount(rewardToken); } } function updateRewardRecord(address _token, uint256 _index) public { require(msg.sender == address(rewardManager), "Only reward manager!"); rewardStakeHistory[_token][_index] = totalStaked; } function updateToken(IERC20MetadataUpgradeable _token) public onlyOwner { require(address(_token) != address(0), "token address cannot be 0"); token = _token; } function updateTimeStep(uint256 _timeStep) public onlyOwner { timeStep = _timeStep; } function setBasePercent(uint256 _basePercent) public onlyOwner { basePercent = _basePercent; } function setPercentDivider(uint256 _percentDivider) public onlyOwner { percentDivider = _percentDivider; } function setRewardManager( IRewardManager _rewardManager ) external onlyOwner { rewardManager = _rewardManager; } function setUsdtStaking(address _addr) external onlyOwner { usdtStaking = _addr; } }
3,816,197
[ 1, 7520, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 840, 495, 352, 510, 6159, 58, 22, 353, 10188, 6934, 16, 14223, 6914, 10784, 429, 288, 203, 565, 1450, 14060, 10477, 10784, 429, 364, 2254, 5034, 31, 203, 203, 565, 467, 654, 39, 3462, 2277, 10784, 429, 1071, 1147, 31, 203, 565, 2254, 5034, 1071, 2078, 510, 9477, 31, 203, 565, 2254, 5034, 1071, 1131, 758, 1724, 31, 203, 565, 2254, 5034, 1071, 813, 4160, 31, 203, 565, 2254, 5034, 1071, 5551, 25558, 31, 203, 565, 2254, 5034, 1071, 1026, 8410, 31, 203, 565, 2254, 5034, 1071, 3089, 510, 581, 414, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 2643, 31, 203, 565, 445, 4046, 12, 45, 654, 39, 3462, 2277, 10784, 429, 389, 2316, 13, 3903, 12562, 288, 203, 3639, 1001, 5460, 429, 67, 2738, 5621, 203, 203, 3639, 1147, 273, 389, 2316, 31, 203, 3639, 1131, 758, 1724, 273, 2130, 380, 1728, 2826, 1147, 18, 31734, 5621, 203, 3639, 813, 4160, 273, 5045, 4681, 31, 203, 3639, 5551, 25558, 273, 2130, 67, 713, 31, 203, 3639, 1026, 8410, 273, 1728, 31, 203, 565, 289, 203, 203, 565, 1958, 2177, 288, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 2254, 5034, 9776, 31, 203, 3639, 2254, 5034, 7516, 329, 17631, 1060, 31, 203, 3639, 2254, 5034, 2078, 14784, 329, 31, 203, 3639, 2254, 5034, 19890, 31, 203, 3639, 2254, 5034, 8657, 31, 203, 3639, 2254, 5034, 598, 9446, 950, 31, 203, 3639, 1426, 15083, 31, 203, 3639, 1426, 353, 4002, 31, 203, 565, 289, 203, 565, 2874, 12, 2 ]
./partial_match/4/0x1D48Ff980B8AaD8e8CCC563eF7cd162720d88ff1/sources/MultiSigWallet.sol
@dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. @param _required Number of required confirmations.
function changeRequirement(uint256 _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); }
8,635,211
[ 1, 19132, 358, 2549, 326, 1300, 434, 1931, 6932, 1012, 18, 5947, 711, 358, 506, 3271, 635, 9230, 18, 225, 389, 4718, 3588, 434, 1931, 6932, 1012, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 18599, 12, 11890, 5034, 389, 4718, 13, 203, 3639, 1071, 203, 3639, 1338, 16936, 203, 3639, 923, 18599, 12, 995, 414, 18, 2469, 16, 389, 4718, 13, 203, 565, 288, 203, 3639, 1931, 273, 389, 4718, 31, 203, 3639, 30813, 3043, 24899, 4718, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x89B3EfA63648B65bc2999BbB4f82bfEd5F83F178 //Contract name: BCFLeague //Balance: 0 Ether //Verification Date: 3/17/2018 //Transacion Count: 25 // CODE STARTS HERE contract BCFBaseCompetition { address public owner; address public referee; bool public paused = false; modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyReferee() { require(msg.sender == referee); _; } function setOwner(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } function setReferee(address newReferee) public onlyOwner { require(newReferee != address(0)); referee = newReferee; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; } function unpause() onlyOwner whenPaused public { paused = false; } } contract BCFMain { function isOwnerOfAllPlayerCards(uint256[], address) public pure returns (bool) {} function implementsERC721() public pure returns (bool) {} function getPlayerForCard(uint) external pure returns ( uint8, uint8, uint8, uint8, uint8, uint8, uint8, uint8, bytes, string, uint8 ) {} } // TODO: Validate that the user has sent the correct ENTRY_FEE and refund them if more, revert if less // TODO: Validate formation type // TODO: Validate that there's at least 1 goalkeeper? // TODO: Validate the team name is under a certain number of characters? // TODO: Do we need to copy these values across to the contract storage? // TODO: Should the frontend do the sorting and league tables? We still need the business logic to determine final positions, // but we don't need to calculate this every round, not doing so would reduce gas consumption // TODO: Need to work out whether it's more gas effecient to read player info every round or store it once and have it? contract BCFLeague is BCFBaseCompetition { struct Team { address manager; bytes name; uint[] cardIds; uint gkCardId; uint8 wins; uint8 losses; uint8 draws; uint16 goalsFor; uint16 goalsAgainst; } struct Match { uint8 homeTeamId; uint8 awayTeamId; uint[] homeScorerIds; uint[] awayScorerIds; bool isFinished; } // Configuration - this will be set in the constructor, hence not being constants uint public TEAMS_TOTAL; uint public ENTRY_FEE; uint public SQUAD_SIZE; uint public TOTAL_ROUNDS; uint public MATCHES_PER_ROUND; uint public SECONDS_BETWEEN_ROUNDS; // Status enum CompetitionStatuses { Upcoming, OpenForEntry, PendingStart, Started, Finished, Settled } CompetitionStatuses public competitionStatus; uint public startedAt; uint public nextRoundStartsAt; int public currentRoundId = -1; // As we may have a round 0 so we don't want to default there // Local Data Lookups Team[] public teams; mapping(address => uint) internal managerToTeamId; mapping(uint => bool) internal cardIdToEntryStatus; mapping(uint => Match[]) internal roundIdToMatches; // Data Source BCFMain public mainContract; // Prize Pool uint public constant PRIZE_POT_PERCENTAGE_MAX = 10000; // 10,000 = 100% so we get 2 digits of precision, 375 = 3.75% uint public prizePool; // Holds the total prize pool uint[] public prizeBreakdown; // Max 10,000 across all indexes. Holds breakdown by index, e.g. [0] 5000 = 50%, [1] 3500 = 35%, [2] 1500 = 15% address[] public winners; // Corresponding array of winners for the prize pot, [0] = first placed winner function BCFLeague(address dataStoreAddress, uint teamsTotal, uint entryFee, uint squadSize, uint roundTimeSecs) public { require(teamsTotal % 2 == 0); // We only allow an even number of teams, this reduces complexity require(teamsTotal > 0); require(roundTimeSecs > 30 seconds && roundTimeSecs < 60 minutes); require(entryFee >= 0); require(squadSize > 0); // Initial state owner = msg.sender; referee = msg.sender; // League configuration TEAMS_TOTAL = teamsTotal; ENTRY_FEE = entryFee; SQUAD_SIZE = squadSize; TOTAL_ROUNDS = TEAMS_TOTAL - 1; MATCHES_PER_ROUND = TEAMS_TOTAL / 2; SECONDS_BETWEEN_ROUNDS = roundTimeSecs; // Always start it as an upcoming league competitionStatus = CompetitionStatuses.Upcoming; // Set the data source BCFMain candidateDataStoreContract = BCFMain(dataStoreAddress); require(candidateDataStoreContract.implementsERC721()); mainContract = candidateDataStoreContract; } // **Gas guzzler** // CURRENT GAS CONSUMPTION: 6339356 function generateFixtures() external onlyOwner { require(competitionStatus == CompetitionStatuses.Upcoming); // Generate the fixtures using a cycling algorithm: for (uint round = 0; round < TOTAL_ROUNDS; round++) { for (uint matchIndex = 0; matchIndex < MATCHES_PER_ROUND; matchIndex++) { uint home = (round + matchIndex) % (TEAMS_TOTAL - 1); uint away = (TEAMS_TOTAL - 1 - matchIndex + round) % (TEAMS_TOTAL - 1); if (matchIndex == 0) { away = TEAMS_TOTAL - 1; } Match memory _match; _match.homeTeamId = uint8(home); _match.awayTeamId = uint8(away); roundIdToMatches[round].push(_match); } } } function createPrizePool(uint[] prizeStructure) external payable onlyOwner { require(competitionStatus == CompetitionStatuses.Upcoming); require(msg.value > 0 && msg.value <= 2 ether); // Set some sensible top and bottom values require(prizeStructure.length > 0); // Can't create a prize pool with no breakdown structure uint allocationTotal = 0; for (uint i = 0; i < prizeStructure.length; i++) { allocationTotal += prizeStructure[i]; } require(allocationTotal > 0 && allocationTotal <= PRIZE_POT_PERCENTAGE_MAX); // Make sure we don't allocate more than 100% of the prize pool or 0% prizePool += msg.value; prizeBreakdown = prizeStructure; } function openCompetition() external onlyOwner whenNotPaused { competitionStatus = CompetitionStatuses.OpenForEntry; } function startCompetition() external onlyReferee whenNotPaused { require(competitionStatus == CompetitionStatuses.PendingStart); // Move the status into Started competitionStatus = CompetitionStatuses.Started; // Mark the startedAt to now startedAt = now; nextRoundStartsAt = now + 60 seconds; } function calculateMatchOutcomesForRoundId(int roundId) external onlyReferee whenNotPaused { require(competitionStatus == CompetitionStatuses.Started); require(nextRoundStartsAt > 0); require(roundId == currentRoundId + 1); // We're only allowed to process the next round, we can't skip ahead require(now > nextRoundStartsAt); // Increment the round counter // We complete the below first as during the calculateScorersForTeamIds we go off to another contract to fetch the // current player attributes so to avoid re-entrancy we bump this first currentRoundId++; // As the total rounds aren't index based we need to compare it to the index+1 // this should never overrun as the gas cost of generating a league with more 20 teams makes this impossible if (TOTAL_ROUNDS == uint(currentRoundId + 1)) { competitionStatus = CompetitionStatuses.Finished; } else { nextRoundStartsAt = now + SECONDS_BETWEEN_ROUNDS; } // Actually calculate some of the outcomes Match[] memory matches = roundIdToMatches[uint(roundId)]; for (uint i = 0; i < matches.length; i++) { Match memory _match = matches[i]; var (homeScorers, awayScorers) = calculateScorersForTeamIds(_match.homeTeamId, _match.awayTeamId); // Adjust the table values updateTeamsTableAttributes(_match.homeTeamId, homeScorers.length, _match.awayTeamId, awayScorers.length); // Save the goal scorers for this match and mark as finished roundIdToMatches[uint(roundId)][i].isFinished = true; roundIdToMatches[uint(roundId)][i].homeScorerIds = homeScorers; roundIdToMatches[uint(roundId)][i].awayScorerIds = awayScorers; } } function updateTeamsTableAttributes(uint homeTeamId, uint homeGoals, uint awayTeamId, uint awayGoals) internal { // GOALS FOR teams[homeTeamId].goalsFor += uint16(homeGoals); teams[awayTeamId].goalsFor += uint16(awayGoals); // GOALS AGAINST teams[homeTeamId].goalsAgainst += uint16(awayGoals); teams[awayTeamId].goalsAgainst += uint16(homeGoals); // WINS / LOSSES / DRAWS if (homeGoals == awayGoals) { teams[homeTeamId].draws++; teams[awayTeamId].draws++; } else if (homeGoals > awayGoals) { teams[homeTeamId].wins++; teams[awayTeamId].losses++; } else { teams[awayTeamId].wins++; teams[homeTeamId].losses++; } } function getAllMatchesForRoundId(uint roundId) public view returns (uint[], uint[], bool[]) { Match[] memory matches = roundIdToMatches[roundId]; uint[] memory _homeTeamIds = new uint[](matches.length); uint[] memory _awayTeamIds = new uint[](matches.length); bool[] memory matchStates = new bool[](matches.length); for (uint i = 0; i < matches.length; i++) { _homeTeamIds[i] = matches[i].homeTeamId; _awayTeamIds[i] = matches[i].awayTeamId; matchStates[i] = matches[i].isFinished; } return (_homeTeamIds, _awayTeamIds, matchStates); } function getMatchAtRoundIdAtIndex(uint roundId, uint index) public view returns (uint, uint, uint[], uint[], bool) { Match[] memory matches = roundIdToMatches[roundId]; Match memory _match = matches[index]; return (_match.homeTeamId, _match.awayTeamId, _match.homeScorerIds, _match.awayScorerIds, _match.isFinished); } function getPlayerCardIdsForTeam(uint teamId) public view returns (uint[]) { Team memory _team = teams[teamId]; return _team.cardIds; } function enterLeague(uint[] cardIds, uint gkCardId, bytes teamName) public payable whenNotPaused { require(mainContract != address(0)); // Must have a valid data store to check card ownership require(competitionStatus == CompetitionStatuses.OpenForEntry); // Competition must be open for entry require(cardIds.length == SQUAD_SIZE); // Require a valid number of players require(teamName.length > 3 && teamName.length < 18); // Require a valid team name require(!hasEntered(msg.sender)); // Make sure the address hasn't already entered require(!hasPreviouslyEnteredCardIds(cardIds)); // Require that none of the players have previously entered, avoiding managers swapping players between accounts require(mainContract.isOwnerOfAllPlayerCards(cardIds, msg.sender)); // User must actually own these cards require(teams.length < TEAMS_TOTAL); // We shouldn't ever hit this as the state should be managed, but just as a fallback require(msg.value >= ENTRY_FEE); // User must have paid a valid entry fee // Create a team and hold the teamId Team memory _team; _team.name = teamName; _team.manager = msg.sender; _team.cardIds = cardIds; _team.gkCardId = gkCardId; uint teamId = teams.push(_team) - 1; // Keep track of who the manager is managing managerToTeamId[msg.sender] = teamId; // Track which team each card plays for for (uint i = 0; i < cardIds.length; i++) { cardIdToEntryStatus[cardIds[i]] = true; } // If we've hit the team limit we can move the contract into the PendingStart status if (teams.length == TEAMS_TOTAL) { competitionStatus = CompetitionStatuses.PendingStart; } } function hasPreviouslyEnteredCardIds(uint[] cardIds) view internal returns (bool) { if (teams.length == 0) { return false; } // This should only ever be a maximum of 5 iterations or 11 for (uint i = 0; i < cardIds.length; i++) { uint cardId = cardIds[i]; bool hasEnteredCardPreviously = cardIdToEntryStatus[cardId]; if (hasEnteredCardPreviously) { return true; } } return false; } function hasEntered(address manager) view internal returns (bool) { if (teams.length == 0) { return false; } // We have to lookup the team AND check the fields because of some of the workings of solidity // 1. We could have a team at index 0, so we CAN'T just check the index is > 0 // 2. Solidity intializes with an empty set of struct values, so we need to do equality on the manager field uint teamIndex = managerToTeamId[manager]; Team memory team = teams[teamIndex]; if (team.manager == manager) { return true; } return false; } function setMainContract(address _address) external onlyOwner { BCFMain candidateContract = BCFMain(_address); require(candidateContract.implementsERC721()); mainContract = candidateContract; } // ** Match Simulator ** function calculateScorersForTeamIds(uint homeTeamId, uint awayTeamId) internal view returns (uint[], uint[]) { var (homeTotals, homeCardsShootingAttributes) = calculateAttributeTotals(homeTeamId); var (awayTotals, awayCardsShootingAttributes) = calculateAttributeTotals(awayTeamId); uint startSeed = now; var (homeGoals, awayGoals) = calculateGoalsFromAttributeTotals(homeTeamId, awayTeamId, homeTotals, awayTotals, startSeed); uint[] memory homeScorers = new uint[](homeGoals); uint[] memory awayScorers = new uint[](awayGoals); // Home Scorers for (uint i = 0; i < homeScorers.length; i++) { homeScorers[i] = determineGoalScoringCardIds(teams[homeTeamId].cardIds, homeCardsShootingAttributes, i); } // Away Scorers for (i = 0; i < awayScorers.length; i++) { awayScorers[i] = determineGoalScoringCardIds(teams[awayTeamId].cardIds, awayCardsShootingAttributes, i); } return (homeScorers, awayScorers); } function calculateGoalsFromAttributeTotals(uint homeTeamId, uint awayTeamId, uint[] homeTotals, uint[] awayTotals, uint startSeed) internal view returns (uint _homeGoals, uint _awayGoals) { uint[] memory atkAttributes = new uint[](3); // 0 = possession, 1 = chance, 2 = shooting uint[] memory defAttributes = new uint[](3); // 0 = regain posession, 1 = prevent chance, 3 = save shot uint attackingTeamId = 0; uint defendingTeamId = 0; uint outcome = 0; uint seed = startSeed * homeTotals[0] * awayTotals[0]; for (uint i = 0; i < 45; i++) { attackingTeamId = determineAttackingOrDefendingOutcomeForAttributes(homeTeamId, awayTeamId, homeTotals[0], awayTotals[0], seed+now); seed++; if (attackingTeamId == homeTeamId) { defendingTeamId = awayTeamId; atkAttributes[0] = homeTotals[3]; // Passing atkAttributes[1] = homeTotals[4]; // Dribbling atkAttributes[2] = homeTotals[2]; // Shooting defAttributes[0] = awayTotals[1]; // Pace defAttributes[1] = awayTotals[6]; // Physical defAttributes[2] = awayTotals[5]; // Defending } else { defendingTeamId = homeTeamId; atkAttributes[0] = awayTotals[3]; // Passing atkAttributes[1] = awayTotals[4]; // Dribbling atkAttributes[2] = awayTotals[2]; // Shooting defAttributes[0] = homeTotals[1]; // Pace defAttributes[1] = homeTotals[6]; // Physical defAttributes[2] = homeTotals[5]; // Defending } outcome = determineAttackingOrDefendingOutcomeForAttributes(attackingTeamId, defendingTeamId, atkAttributes[0], defAttributes[0], seed); if (outcome == defendingTeamId) { // Attack broken up continue; } seed++; outcome = determineAttackingOrDefendingOutcomeForAttributes(attackingTeamId, defendingTeamId, atkAttributes[1], defAttributes[1], seed); if (outcome == defendingTeamId) { // Chance prevented continue; } seed++; outcome = determineAttackingOrDefendingOutcomeForAttributes(attackingTeamId, defendingTeamId, atkAttributes[2], defAttributes[2], seed); if (outcome == defendingTeamId) { // Shot saved continue; } // GOAL - determine whether it was the home team who scored or the away team if (attackingTeamId == homeTeamId) { // Home goal _homeGoals += 1; } else { // Away goal _awayGoals += 1; } } } function calculateAttributeTotals(uint teamId) internal view returns (uint[], uint[]) { // NOTE: We store these in an array because of stack too deep errors from Solidity, // We could seperate these out but in the end it will end up being uniweildly // this is the case in subsquent arrays too, while not perfect does give us a bit more flexibility uint[] memory totals = new uint[](7); uint[] memory cardsShootingAttributes = new uint[](SQUAD_SIZE); Team memory _team = teams[teamId]; for (uint i = 0; i < SQUAD_SIZE; i++) { var (overall,pace,shooting,passing,dribbling,defending,physical,,,,) = mainContract.getPlayerForCard(_team.cardIds[i]); // If it's a goalie we forego attack for increased shot stopping avbility if (_team.cardIds[i] == _team.gkCardId && _team.gkCardId > 0) { totals[5] += (overall * 5); totals[6] += overall; cardsShootingAttributes[i] = 1; // Almost no chance for the GK to score } else { totals[0] += overall; totals[1] += pace; totals[2] += shooting; totals[3] += passing; totals[4] += dribbling; totals[5] += defending; totals[6] += physical; cardsShootingAttributes[i] = shooting + dribbling; // Chance to score by combining shooting and dribbling } } return (totals, cardsShootingAttributes); } function determineAttackingOrDefendingOutcomeForAttributes(uint attackingTeamId, uint defendingTeamId, uint atkAttributeTotal, uint defAttributeTotal, uint seed) internal view returns (uint) { uint max = atkAttributeTotal + defAttributeTotal; uint randValue = uint(keccak256(block.blockhash(block.number-1), seed))%max; if (randValue <= atkAttributeTotal) { return attackingTeamId; } return defendingTeamId; } function determineGoalScoringCardIds(uint[] cardIds, uint[] shootingAttributes, uint seed) internal view returns(uint) { uint max = 0; uint min = 0; for (uint i = 0; i < shootingAttributes.length; i++) { max += shootingAttributes[i]; } bytes32 randHash = keccak256(seed, now, block.blockhash(block.number - 1)); uint randValue = uint(randHash) % max + min; for (i = 0; i < cardIds.length; i++) { uint cardId = cardIds[i]; randValue -= shootingAttributes[i]; // We do the more than to handle wrap arounds on uint if (randValue <= 0 || randValue >= max) { return cardId; } } return cardIds[0]; } // ** Settlement ** function calculateWinningEntries() external onlyReferee { require(competitionStatus == CompetitionStatuses.Finished); address[] memory winningAddresses = new address[](prizeBreakdown.length); uint[] memory winningTeamIds = new uint[](prizeBreakdown.length); uint[] memory winningTeamPoints = new uint[](prizeBreakdown.length); // League table position priority // 1. Most Points // 2. Biggest Goal Difference // 3. Most Goals Scored // 4. Number of Wins // 5. First to Enter // 1. Loop over all teams bool isReplacementWinner = false; for (uint i = 0; i < teams.length; i++) { Team memory _team = teams[i]; // 2. Grab their current points uint currPoints = (_team.wins * 3) + _team.draws; // 3. Compare the points to each team in the winning team points array for (uint x = 0; x < winningTeamPoints.length; x++) { // 4. Check if the current entry is more isReplacementWinner = false; if (currPoints > winningTeamPoints[x]) { isReplacementWinner = true; // 5. We need to handle tie-break rules if 2 teams have the same number of points } else if (currPoints == winningTeamPoints[x]) { // 5a. Unfortunately in this scenario we need to refetch the team we're comparing Team memory _comparisonTeam = teams[winningTeamIds[x]]; int gdTeam = _team.goalsFor - _team.goalsAgainst; int gdComparedTeam = _comparisonTeam.goalsFor - _comparisonTeam.goalsAgainst; // 5b. GOAL DIFFERENCE if (gdTeam > gdComparedTeam) { isReplacementWinner = true; } else if (gdTeam == gdComparedTeam) { // 5c. MOST GOALS if (_team.goalsFor > _comparisonTeam.goalsFor) { isReplacementWinner = true; } else if (_team.goalsFor == _comparisonTeam.goalsFor) { // 5d. NUMBER OF WINS if (_team.wins > _comparisonTeam.wins) { isReplacementWinner = true; } else if (_team.wins == _comparisonTeam.wins) { // 5e. FIRST TO ENTER (LOWER INDEX) if (i < winningTeamIds[x]) { isReplacementWinner = true; } } } } } // 6. Now we need to shift all elements down for the "paid places" for winning entries if (isReplacementWinner) { // 7. We need to start by copying the current index into next one down, assuming it exists for (uint y = winningAddresses.length - 1; y > x; y--) { winningAddresses[y] = winningAddresses[y-1]; winningTeamPoints[y] = winningTeamPoints[y-1]; winningTeamIds[y] = winningTeamIds[y-1]; } // 8. Set the current team and points as a replacemenet for the current entry winningAddresses[x] = _team.manager; winningTeamPoints[x] = currPoints; winningTeamIds[x] = i; break; // We don't need to compare values further down the chain } } } // Set the winning entries winners = winningAddresses; } function settleLeague() external onlyOwner { require(competitionStatus == CompetitionStatuses.Finished); require(winners.length > 0); require(prizeBreakdown.length == winners.length); require(prizePool >= this.balance); // Mark the contest as settled competitionStatus = CompetitionStatuses.Settled; // Payout each winner for (uint i = 0; i < winners.length; i++) { address winner = winners[i]; uint percentageCut = prizeBreakdown[i]; // We can assume this index exists as we've checked the lengths in the require uint winningAmount = calculateWinnerCut(prizePool, percentageCut); winner.transfer(winningAmount); } } function calculateWinnerCut(uint totalPot, uint cut) internal pure returns (uint256) { // PRIZE_POT_PERCENTAGE_MAX = 10,000 = 100%, required'd <= PRIZE_POT_PERCENTAGE_MAX in the constructor so no requirement to validate here uint finalCut = totalPot * cut / PRIZE_POT_PERCENTAGE_MAX; return finalCut; } function withdrawBalance() external onlyOwner { owner.transfer(this.balance); } // Utils function hasStarted() external view returns (bool) { if (competitionStatus == CompetitionStatuses.Upcoming || competitionStatus == CompetitionStatuses.OpenForEntry || competitionStatus == CompetitionStatuses.PendingStart) { return false; } return true; } function winningTeamId() external view returns (uint) { require(competitionStatus == CompetitionStatuses.Finished || competitionStatus == CompetitionStatuses.Settled); uint winningTeamId = 0; for (uint i = 0; i < teams.length; i++) { if (teams[i].manager == winners[0]) { winningTeamId = i; break; } } return winningTeamId; } }
Require a valid number of players
require(cardIds.length == SQUAD_SIZE);
12,782,315
[ 1, 8115, 279, 923, 1300, 434, 18115, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 3327, 2673, 18, 2469, 422, 348, 3500, 1880, 67, 4574, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.6.8 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // 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)); } } // File @openzeppelin/contracts/utils/[email protected] // 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); } } } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract 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()); } } } // File contracts/fei-protocol/external/SafeMathCopy.sol // 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 SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap safemath /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/fei-protocol/external/Decimal.sol /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> 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.0; pragma experimental ABIEncoderV2; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMathCopy for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // File contracts/fei-protocol/bondingcurve/IBondingCurve.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface IBondingCurve { // ----------- Events ----------- event ScaleUpdate(uint _scale); event BufferUpdate(uint _buffer); event Purchase(address indexed _to, uint _amountIn, uint _amountOut); event Allocate(address indexed _caller, uint _amount); // ----------- State changing Api ----------- /// @notice purchase FEI for underlying tokens /// @param to address to receive FEI /// @param amountIn amount of underlying tokens input /// @return amountOut amount of FEI received function purchase(address to, uint amountIn) external payable returns (uint amountOut); /// @notice batch allocate held PCV function allocate() external; // ----------- Governor only state changing api ----------- /// @notice sets the bonding curve price buffer function setBuffer(uint _buffer) external; /// @notice sets the bonding curve Scale target function setScale(uint _scale) external; /// @notice sets the allocation of incoming PCV function setAllocation(address[] calldata pcvDeposits, uint[] calldata ratios) external; // ----------- Getters ----------- /// @notice return current instantaneous bonding curve price /// @return price reported as FEI per X with X being the underlying asset function getCurrentPrice() external view returns(Decimal.D256 memory); /// @notice return the average price of a transaction along bonding curve /// @param amountIn the amount of underlying used to purchase /// @return price reported as FEI per X with X being the underlying asset function getAveragePrice(uint amountIn) external view returns (Decimal.D256 memory); /// @notice return amount of FEI received after a bonding curve purchase /// @param amountIn the amount of underlying used to purchase /// @return amountOut the amount of FEI received function getAmountOut(uint amountIn) external view returns (uint amountOut); /// @notice the Scale target at which bonding curve price fixes function scale() external view returns (uint); /// @notice a boolean signalling whether Scale has been reached function atScale() external view returns (bool); /// @notice the buffer applied on top of the peg purchase price once at Scale function buffer() external view returns(uint); /// @notice the total amount of FEI purchased on bonding curve. FEI_b from the whitepaper function totalPurchased() external view returns(uint); /// @notice the amount of PCV held in contract and ready to be allocated function getTotalPCVHeld() external view returns(uint); /// @notice amount of FEI paid for allocation when incentivized function incentiveAmount() external view returns(uint); } // File @uniswap/lib/contracts/libraries/[email protected] // 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); } } // File contracts/fei-protocol/utils/Roots.sol pragma solidity ^0.6.0; library Roots { // Newton's method https://en.wikipedia.org/wiki/Cube_root#Numerical_methods function cubeRoot(uint y) internal pure returns (uint z) { if (y > 7) { z = y; uint x = y / 3 + 1; while (x < z) { z = x; x = (y / (x * x) + (2 * x)) / 3; } } else if (y != 0) { z = 1; } } // x^(3/2); function threeHalfsRoot(uint x) internal pure returns (uint) { return sqrt(x) ** 3; } // x^(2/3); function twoThirdsRoot(uint x) internal pure returns (uint) { return cubeRoot(x) ** 2; } function sqrt(uint y) internal pure returns (uint) { return Babylonian.sqrt(y); } } // File contracts/fei-protocol/oracle/IOracle.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title generic oracle interface for Fei Protocol /// @author Fei Protocol interface IOracle { // ----------- Events ----------- event KillSwitchUpdate(bool _killSwitch); event Update(uint _peg); // ----------- State changing API ----------- /// @notice updates the oracle price /// @return true if oracle is updated and false if unchanged function update() external returns (bool); // ----------- Governor only state changing API ----------- /// @notice sets the kill switch on the oracle feed /// @param _killSwitch the new value for the kill switch function setKillSwitch(bool _killSwitch) external; // ----------- Getters ----------- /// @notice read the oracle price /// @return oracle price /// @return true if price is valid /// @dev price is to be denominated in USD per X where X can be ETH, etc. function read() external view returns (Decimal.D256 memory, bool); /// @notice the kill switch for the oracle feed /// @return true if kill switch engaged /// @dev if kill switch is true, read will return invalid function killSwitch() external view returns (bool); } // File contracts/fei-protocol/refs/IOracleRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title A oracle Reference contract /// @author Fei Protocol /// @notice defines some utilities around interacting with the referenced oracle interface IOracleRef { // ----------- Events ----------- event OracleUpdate(address indexed _oracle); // ----------- State changing API ----------- /// @notice updates the referenced oracle /// @return true if the update is effective function updateOracle() external returns(bool); // ----------- Governor only state changing API ----------- /// @notice sets the referenced oracle /// @param _oracle the new oracle to reference function setOracle(address _oracle) external; // ----------- Getters ----------- /// @notice the oracle reference by the contract /// @return the IOracle implementation address function oracle() external view returns(IOracle); /// @notice the peg price of the referenced oracle /// @return the peg as a Decimal /// @dev the peg is defined as FEI per X with X being ETH, dollars, etc function peg() external view returns(Decimal.D256 memory); /// @notice invert a peg price /// @param price the peg price to invert /// @return the inverted peg as a Decimal /// @dev the inverted peg would be X per FEI function invert(Decimal.D256 calldata price) external pure returns(Decimal.D256 memory); } // File @openzeppelin/contracts/token/ERC20/[email protected] // 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); } // File contracts/fei-protocol/token/IFei.sol pragma solidity ^0.6.2; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting(address indexed _to, address indexed _minter, uint _amount); event Burning(address indexed _to, address indexed _burner, uint _amount); event IncentiveContractUpdate(address indexed _incentivized, address indexed _incentiveContract); // ----------- State changing api ----------- /// @notice burn FEI tokens from caller /// @param amount the amount to burn function burn(uint amount) external; // ----------- Burner only state changing api ----------- /// @notice burn FEI tokens from specified account /// @param account the account to burn from /// @param amount the amount to burn function burnFrom(address account, uint amount) external; // ----------- Minter only state changing api ----------- /// @notice mint FEI tokens /// @param account the account to mint to /// @param amount the amount to mint function mint(address account, uint amount) external; // ----------- Governor only state changing api ----------- /// @param account the account to incentivize /// @param incentive the associated incentive contract function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- /// @notice get associated incentive contract /// @param account the address to check /// @return the associated incentive contract, 0 address if N/A function incentiveContract(address account) external view returns(address); } // File contracts/fei-protocol/core/IPermissions.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Access control module for Core /// @author Fei Protocol interface IPermissions { // Governor only state changing api /// @notice creates a new role to be maintained /// @param role the new role id /// @param adminRole the admin role id for `role` /// @dev can also be used to update admin of existing role function createRole(bytes32 role, bytes32 adminRole) external; /// @notice grants minter role to address /// @param minter new minter function grantMinter(address minter) external; /// @notice grants burner role to address /// @param burner new burner function grantBurner(address burner) external; /// @notice grants controller role to address /// @param pcvController new controller function grantPCVController(address pcvController) external; /// @notice grants governor role to address /// @param governor new governor function grantGovernor(address governor) external; /// @notice grants revoker role to address /// @param revoker new revoker function grantRevoker(address revoker) external; /// @notice revokes minter role from address /// @param minter ex minter function revokeMinter(address minter) external; /// @notice revokes burner role from address /// @param burner ex burner function revokeBurner(address burner) external; /// @notice revokes pcvController role from address /// @param pcvController ex pcvController function revokePCVController(address pcvController) external; /// @notice revokes governor role from address /// @param governor ex governor function revokeGovernor(address governor) external; /// @notice revokes revoker role from address /// @param revoker ex revoker function revokeRevoker(address revoker) external; // Revoker only state changing api /// @notice revokes a role from address /// @param role the role to revoke /// @param account the address to revoke the role from function revokeOverride(bytes32 role, address account) external; // Getters /// @notice checks if address is a burner /// @param _address address to check /// @return true _address is a burner function isBurner(address _address) external view returns (bool); /// @notice checks if address is a minter /// @param _address address to check /// @return true _address is a minter function isMinter(address _address) external view returns (bool); /// @notice checks if address is a governor /// @param _address address to check /// @return true _address is a governor function isGovernor(address _address) external view returns (bool); /// @notice checks if address is a revoker /// @param _address address to check /// @return true _address is a revoker function isRevoker(address _address) external view returns (bool); /// @notice checks if address is a controller /// @param _address address to check /// @return true _address is a controller function isPCVController(address _address) external view returns (bool); } // File contracts/fei-protocol/core/ICore.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Source of truth for Fei Protocol /// @author Fei Protocol /// @notice maintains roles, access control, fei, tribe, genesisGroup, and the TRIBE treasury interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeAllocation(address indexed _to, uint _amount); event GenesisPeriodComplete(uint _timestamp); // ----------- Governor only state changing api ----------- /// @notice sets Fei address to a new address /// @param token new fei address function setFei(address token) external; /// @notice sets Genesis Group address /// @param _genesisGroup new genesis group address function setGenesisGroup(address _genesisGroup) external; /// @notice sends TRIBE tokens from treasury to an address /// @param to the address to send TRIBE to /// @param amount the amount of TRIBE to send function allocateTribe(address to, uint amount) external; // ----------- Genesis Group only state changing api ----------- /// @notice marks the end of the genesis period /// @dev can only be called once function completeGenesisGroup() external; // ----------- Getters ----------- /// @notice the address of the FEI contract /// @return fei contract function fei() external view returns (IFei); /// @notice the address of the TRIBE contract /// @return tribe contract function tribe() external view returns (IERC20); /// @notice the address of the GenesisGroup contract /// @return genesis group contract function genesisGroup() external view returns(address); /// @notice determines whether in genesis period or not /// @return true if in genesis period function hasGenesisGroupCompleted() external view returns(bool); } // File contracts/fei-protocol/refs/ICoreRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title A Core Reference contract /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed _core); // ----------- Governor only state changing api ----------- /// @notice set new Core reference address /// @param core the new core address function setCore(address core) external; // ----------- Getters ----------- /// @notice address of the Core contract referenced /// @return ICore implementation address function core() external view returns (ICore); /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() external view returns (IFei); /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() external view returns (IERC20); /// @notice fei balance of contract /// @return fei amount held function feiBalance() external view returns(uint); /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() external view returns(uint); } // File contracts/fei-protocol/refs/CoreRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Abstract implementation of ICoreRef /// @author Fei Protocol abstract contract CoreRef is ICoreRef { ICore private _core; /// @notice CoreRef constructor /// @param core Fei Core to reference constructor(address core) public { _core = ICore(core); } modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier ifBurnerSelf() { if (_core.isBurner(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require(_core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller"); _; } modifier onlyGovernor() { require(_core.isGovernor(msg.sender), "CoreRef: Caller is not a governor"); _; } modifier onlyFei() { require(msg.sender == address(fei()), "CoreRef: Caller is not FEI"); _; } modifier onlyGenesisGroup() { require(msg.sender == _core.genesisGroup(), "CoreRef: Caller is not GenesisGroup"); _; } modifier postGenesis() { require(_core.hasGenesisGroupCompleted(), "CoreRef: Still in Genesis Period"); _; } function setCore(address core) external override onlyGovernor { _core = ICore(core); emit CoreUpdate(core); } function core() public view override returns(ICore) { return _core; } function fei() public view override returns(IFei) { return _core.fei(); } function tribe() public view override returns(IERC20) { return _core.tribe(); } function feiBalance() public view override returns (uint) { return fei().balanceOf(address(this)); } function tribeBalance() public view override returns (uint) { return tribe().balanceOf(address(this)); } function _burnFeiHeld() internal { fei().burn(feiBalance()); } function _mintFei(uint amount) internal { fei().mint(address(this), amount); } } // File contracts/fei-protocol/refs/OracleRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Abstract implementation of IOracleRef /// @author Fei Protocol abstract contract OracleRef is IOracleRef, CoreRef { using Decimal for Decimal.D256; IOracle public override oracle; /// @notice OracleRef constructor /// @param _core Fei Core to reference /// @param _oracle oracle to reference constructor(address _core, address _oracle) public CoreRef(_core) { _setOracle(_oracle); } function setOracle(address _oracle) external override onlyGovernor { _setOracle(_oracle); emit OracleUpdate(_oracle); } function invert(Decimal.D256 memory price) public override pure returns(Decimal.D256 memory) { return Decimal.one().div(price); } function updateOracle() public override returns(bool) { return oracle.update(); } function peg() public override view returns(Decimal.D256 memory) { (Decimal.D256 memory _peg, bool valid) = oracle.read(); require(valid, "OracleRef: oracle invalid"); return _peg; } function _setOracle(address _oracle) internal { oracle = IOracle(_oracle); } } // File contracts/fei-protocol/pcv/PCVSplitter.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title abstract contract for splitting PCV into different deposits /// @author Fei Protocol abstract contract PCVSplitter { /// @notice total allocation allowed representing 100% uint public constant ALLOCATION_GRANULARITY = 10_000; uint[] private ratios; address[] private pcvDeposits; event AllocationUpdate(address[] _pcvDeposits, uint[] _ratios); /// @notice PCVSplitter constructor /// @param _pcvDeposits list of PCV Deposits to split to /// @param _ratios ratios for splitting PCV Deposit allocations constructor(address[] memory _pcvDeposits, uint[] memory _ratios) public { _setAllocation(_pcvDeposits, _ratios); } /// @notice make sure an allocation has matching lengths and totals the ALLOCATION_GRANULARITY /// @param _pcvDeposits new list of pcv deposits to send to /// @param _ratios new ratios corresponding to the PCV deposits /// @return true if it is a valid allocation function checkAllocation(address[] memory _pcvDeposits, uint[] memory _ratios) public pure returns (bool) { require(_pcvDeposits.length == _ratios.length, "PCVSplitter: PCV Deposits and ratios are different lengths"); uint total; for (uint i; i < _ratios.length; i++) { total += _ratios[i]; } require(total == ALLOCATION_GRANULARITY, "PCVSplitter: ratios do not total 100%"); return true; } /// @notice gets the pcvDeposits and ratios of the splitter function getAllocation() public view returns (address[] memory, uint[] memory) { return (pcvDeposits, ratios); } /// @notice distribute funds to single PCV deposit /// @param amount amount of funds to send /// @param pcvDeposit the pcv deposit to send funds function _allocateSingle(uint amount, address pcvDeposit) internal virtual ; /// @notice sets a new allocation for the splitter /// @param _pcvDeposits new list of pcv deposits to send to /// @param _ratios new ratios corresponding to the PCV deposits. Must total ALLOCATION_GRANULARITY function _setAllocation(address[] memory _pcvDeposits, uint[] memory _ratios) internal { checkAllocation(_pcvDeposits, _ratios); pcvDeposits = _pcvDeposits; ratios = _ratios; emit AllocationUpdate(_pcvDeposits, _ratios); } /// @notice distribute funds to all pcv deposits at specified allocation ratios /// @param total amount of funds to send function _allocate(uint total) internal { uint granularity = ALLOCATION_GRANULARITY; for (uint i; i < ratios.length; i++) { uint amount = total * ratios[i] / granularity; _allocateSingle(amount, pcvDeposits[i]); } } } // File contracts/fei-protocol/utils/SafeMath32.sol // SPDX-License-Identifier: MIT // SafeMath for 32 bit integers inspired by OpenZeppelin SafeMath 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 SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { 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(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 c = a - b; return c; } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File contracts/fei-protocol/utils/Timed.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title an abstract contract for timed events /// @author Fei Protocol abstract contract Timed { using SafeCast for uint; using SafeMath32 for uint32; /// @notice the start timestamp of the timed period uint32 public startTime; /// @notice the duration of the timed period uint32 public duration; constructor(uint32 _duration) public { duration = _duration; } /// @notice return true if time period has ended function isTimeEnded() public view returns (bool) { return remainingTime() == 0; } /// @notice number of seconds remaining until time is up /// @return remaining function remainingTime() public view returns (uint32) { return duration.sub(timestamp()); } /// @notice number of seconds since contract was initialized /// @return timestamp /// @dev will be less than or equal to duration function timestamp() public view returns (uint32) { uint32 d = duration; // solhint-disable-next-line not-rely-on-time uint32 t = now.toUint32().sub(startTime); return t > d ? d : t; } function _initTimed() internal { // solhint-disable-next-line not-rely-on-time startTime = now.toUint32(); } } // File contracts/fei-protocol/bondingcurve/BondingCurve.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title an abstract bonding curve for purchasing FEI /// @author Fei Protocol abstract contract BondingCurve is IBondingCurve, OracleRef, PCVSplitter, Timed { using Decimal for Decimal.D256; using Roots for uint; uint public override scale; uint public override totalPurchased; // FEI_b for this curve uint public override buffer = 100; uint public constant BUFFER_GRANULARITY = 10_000; uint public override incentiveAmount; /// @notice constructor /// @param _scale the Scale target where peg fixes /// @param _core Fei Core to reference /// @param _pcvDeposits the PCV Deposits for the PCVSplitter /// @param _ratios the ratios for the PCVSplitter /// @param _oracle the UniswapOracle to reference /// @param _duration the duration between incentivizing allocations /// @param _incentive the amount rewarded to the caller of an allocation constructor( uint _scale, address _core, address[] memory _pcvDeposits, uint[] memory _ratios, address _oracle, uint32 _duration, uint _incentive ) public OracleRef(_core, _oracle) PCVSplitter(_pcvDeposits, _ratios) Timed(_duration) { _setScale(_scale); incentiveAmount = _incentive; } function setScale(uint _scale) external override onlyGovernor { _setScale(_scale); emit ScaleUpdate(_scale); } function setBuffer(uint _buffer) external override onlyGovernor { require(_buffer < BUFFER_GRANULARITY, "BondingCurve: Buffer exceeds or matches granularity"); buffer = _buffer; emit BufferUpdate(_buffer); } function setAllocation(address[] calldata allocations, uint[] calldata ratios) external override onlyGovernor { _setAllocation(allocations, ratios); } function allocate() external override { uint amount = getTotalPCVHeld(); require(amount != 0, "BondingCurve: No PCV held"); _allocate(amount); _incentivize(); emit Allocate(msg.sender, amount); } function atScale() public override view returns (bool) { return totalPurchased >= scale; } function getCurrentPrice() public view override returns(Decimal.D256 memory) { if (atScale()) { return peg().mul(_getBuffer()); } return peg().div(_getBondingCurvePriceMultiplier()); } function getAmountOut(uint amountIn) public view override returns (uint amountOut) { uint adjustedAmount = getAdjustedAmount(amountIn); if (atScale()) { return _getBufferAdjustedAmount(adjustedAmount); } return _getBondingCurveAmountOut(adjustedAmount); } function getAveragePrice(uint amountIn) public view override returns (Decimal.D256 memory) { uint adjustedAmount = getAdjustedAmount(amountIn); uint amountOut = getAmountOut(amountIn); return Decimal.ratio(adjustedAmount, amountOut); } function getAdjustedAmount(uint amountIn) internal view returns (uint) { return peg().mul(amountIn).asUint256(); } function getTotalPCVHeld() public view override virtual returns(uint); function _purchase(uint amountIn, address to) internal returns (uint amountOut) { updateOracle(); amountOut = getAmountOut(amountIn); incrementTotalPurchased(amountOut); fei().mint(to, amountOut); emit Purchase(to, amountIn, amountOut); return amountOut; } function incrementTotalPurchased(uint amount) internal { totalPurchased += amount; } function _setScale(uint _scale) internal { scale = _scale; } function _incentivize() internal virtual { if (isTimeEnded()) { _initTimed(); fei().mint(msg.sender, incentiveAmount); } } function _getBondingCurvePriceMultiplier() internal view virtual returns(Decimal.D256 memory); function _getBondingCurveAmountOut(uint adjustedAmountIn) internal view virtual returns(uint); function _getBuffer() internal view returns(Decimal.D256 memory) { uint granularity = BUFFER_GRANULARITY; return Decimal.ratio(granularity - buffer, granularity); } function _getBufferAdjustedAmount(uint amountIn) internal view returns(uint) { return _getBuffer().mul(amountIn).asUint256(); } } // File contracts/fei-protocol/pcv/IPCVDeposit.sol pragma solidity ^0.6.2; /// @title a PCV Deposit interface /// @author Fei Protocol interface IPCVDeposit { // ----------- Events ----------- event Deposit(address indexed _from, uint _amount); event Withdrawal(address indexed _caller, address indexed _to, uint _amount); // ----------- State changing api ----------- /// @notice deposit tokens into the PCV allocation /// @param amount of tokens deposited function deposit(uint amount) external payable; // ----------- PCV Controller only state changing api ----------- /// @notice withdraw tokens from the PCV allocation /// @param amount of tokens withdrawn /// @param to the address to send PCV to function withdraw(address to, uint amount) external; // ----------- Getters ----------- /// @notice returns total value of PCV in the Deposit function totalValue() external view returns(uint); } // File contracts/fei-protocol/bondingcurve/EthBondingCurve.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title a square root growth bonding curve for purchasing FEI with ETH /// @author Fei Protocol contract EthBondingCurve is BondingCurve { uint internal immutable SHIFT; // k shift constructor( uint scale, address core, address[] memory pcvDeposits, uint[] memory ratios, address oracle, uint32 duration, uint incentive ) public BondingCurve( scale, core, pcvDeposits, ratios, oracle, duration, incentive ) { SHIFT = scale / 3; // Enforces a .50c starting price per bonding curve formula } function purchase(address to, uint amountIn) external override payable postGenesis returns (uint amountOut) { require(msg.value == amountIn, "Bonding Curve: Sent value does not equal input"); return _purchase(amountIn, to); } function getTotalPCVHeld() public view override returns(uint) { return address(this).balance; } // Represents the integral solved for upper bound of P(x) = ((k+X)/(k+S))^1/2 * O. Subtracting starting point C function _getBondingCurveAmountOut(uint adjustedAmountIn) internal view override returns (uint amountOut) { uint shiftTotal = _shift(totalPurchased); // k + C uint radicand = (3 * adjustedAmountIn * _shift(scale).sqrt() / 2) + shiftTotal.threeHalfsRoot(); return radicand.twoThirdsRoot() - shiftTotal; // result - (k + C) } function _getBondingCurvePriceMultiplier() internal view override returns(Decimal.D256 memory) { return Decimal.ratio(_shift(totalPurchased).sqrt(), _shift(scale).sqrt()); } function _allocateSingle(uint amount, address pcvDeposit) internal override { IPCVDeposit(pcvDeposit).deposit{value : amount}(amount); } function _shift(uint x) internal view returns(uint) { return SHIFT + x; } } // File contracts/fei-protocol/core/Permissions.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title IPermissions implementation /// @author Fei Protocol contract Permissions is IPermissions, AccessControl { bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PCV_CONTROLLER_ROLE = keccak256("PCV_CONTROLLER_ROLE"); bytes32 public constant GOVERN_ROLE = keccak256("GOVERN_ROLE"); bytes32 public constant REVOKE_ROLE = keccak256("REVOKE_ROLE"); constructor() public { _setupGovernor(address(this)); _setRoleAdmin(MINTER_ROLE, GOVERN_ROLE); _setRoleAdmin(BURNER_ROLE, GOVERN_ROLE); _setRoleAdmin(PCV_CONTROLLER_ROLE, GOVERN_ROLE); _setRoleAdmin(GOVERN_ROLE, GOVERN_ROLE); _setRoleAdmin(REVOKE_ROLE, GOVERN_ROLE); } modifier onlyGovernor() { require(isGovernor(msg.sender), "Permissions: Caller is not a governor"); _; } modifier onlyRevoker() { require(isRevoker(msg.sender), "Permissions: Caller is not a revoker"); _; } function createRole(bytes32 role, bytes32 adminRole) external override onlyGovernor { _setRoleAdmin(role, adminRole); } function grantMinter(address minter) external override onlyGovernor { grantRole(MINTER_ROLE, minter); } function grantBurner(address burner) external override onlyGovernor { grantRole(BURNER_ROLE, burner); } function grantPCVController(address pcvController) external override onlyGovernor { grantRole(PCV_CONTROLLER_ROLE, pcvController); } function grantGovernor(address governor) external override onlyGovernor { grantRole(GOVERN_ROLE, governor); } function grantRevoker(address revoker) external override onlyGovernor { grantRole(REVOKE_ROLE, revoker); } function revokeMinter(address minter) external override onlyGovernor { revokeRole(MINTER_ROLE, minter); } function revokeBurner(address burner) external override onlyGovernor { revokeRole(BURNER_ROLE, burner); } function revokePCVController(address pcvController) external override onlyGovernor { revokeRole(PCV_CONTROLLER_ROLE, pcvController); } function revokeGovernor(address governor) external override onlyGovernor { revokeRole(GOVERN_ROLE, governor); } function revokeRevoker(address revoker) external override onlyGovernor { revokeRole(REVOKE_ROLE, revoker); } function revokeOverride(bytes32 role, address account) external override onlyRevoker { this.revokeRole(role, account); } function isMinter(address _address) external override view returns (bool) { return hasRole(MINTER_ROLE, _address); } function isBurner(address _address) external override view returns (bool) { return hasRole(BURNER_ROLE, _address); } function isPCVController(address _address) external override view returns (bool) { return hasRole(PCV_CONTROLLER_ROLE, _address); } // only virtual for testing mock override function isGovernor(address _address) public override view virtual returns (bool) { return hasRole(GOVERN_ROLE, _address); } function isRevoker(address _address) public override view returns (bool) { return hasRole(REVOKE_ROLE, _address); } function _setupGovernor(address governor) internal { _setupRole(GOVERN_ROLE, governor); } } // File @openzeppelin/contracts/math/[email protected] // 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; } } // File @openzeppelin/contracts/token/ERC20/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 { } } // File @openzeppelin/contracts/token/ERC20/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { 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); } } // File contracts/fei-protocol/token/IIncentive.sol pragma solidity ^0.6.2; /// @title incentive contract interface /// @author Fei Protocol /// @notice Called by FEI token contract when transferring with an incentivized address /// @dev should be appointed as a Minter or Burner as needed interface IIncentive { // ----------- Fei only state changing api ----------- /// @notice apply incentives on transfer /// @param sender the sender address of the FEI /// @param receiver the receiver address of the FEI /// @param operator the operator (msg.sender) of the transfer /// @param amount the amount of FEI transferred function incentivize( address sender, address receiver, address operator, uint amount ) external; } // File contracts/fei-protocol/token/Fei.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title IFei implementation /// @author Fei Protocol contract Fei is IFei, ERC20, ERC20Burnable, CoreRef { mapping (address => address) public override incentiveContract; 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; /// @notice Fei token constructor /// @param core Fei Core address to reference constructor(address core) public ERC20("Fei USD", "FEI") CoreRef(core) { 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 setIncentiveContract(address account, address incentive) external override onlyGovernor { incentiveContract[account] = incentive; emit IncentiveContractUpdate(account, incentive); } function mint(address account, uint amount) external override onlyMinter { _mint(account, amount); emit Minting(account, msg.sender, amount); } function burn(uint amount) public override(IFei, ERC20Burnable) { super.burn(amount); emit Burning(msg.sender, msg.sender, amount); } function burnFrom(address account, uint amount) public override(IFei, ERC20Burnable) onlyBurner { _burn(account, amount); emit Burning(account, msg.sender, amount); } function _beforeTokenTransfer(address from, address to, uint amount) internal override { // If not minting or burning if (from != address(0) && to != address(0)) { _checkAndApplyIncentives(from, to, amount); } } function _checkAndApplyIncentives(address sender, address recipient, uint amount) internal { // incentive on sender address senderIncentive = incentiveContract[sender]; if (senderIncentive != address(0)) { IIncentive(senderIncentive).incentivize(sender, recipient, msg.sender, amount); } // incentive on recipient address recipientIncentive = incentiveContract[recipient]; if (recipientIncentive != address(0)) { IIncentive(recipientIncentive).incentivize(sender, recipient, msg.sender, amount); } // incentive on operator address operatorIncentive = incentiveContract[msg.sender]; if (msg.sender != sender && msg.sender != recipient && operatorIncentive != address(0)) { IIncentive(operatorIncentive).incentivize(sender, recipient, msg.sender, amount); } // all incentive address allIncentive = incentiveContract[address(0)]; if (allIncentive != address(0)) { IIncentive(allIncentive).incentivize(sender, recipient, msg.sender, amount); } } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'Fei: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'Fei: INVALID_SIGNATURE'); _approve(owner, spender, value); } } // File contracts/fei-protocol/dao/Tribe.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // Forked from Tribeswap's UNI // Reference: https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code contract Tribe { /// @notice EIP-20 token name for this token // solhint-disable-next-line const-name-snakecase string public constant name = "Tribe"; /// @notice EIP-20 token symbol for this token // solhint-disable-next-line const-name-snakecase string public constant symbol = "TRIBE"; /// @notice EIP-20 token decimals for this token // solhint-disable-next-line const-name-snakecase uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation // solhint-disable-next-line const-name-snakecase uint public totalSupply = 1_000_000_000e18; // 1 billion Tribe /// @notice Address which may mint new tokens address public minter; /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Tribe token * @param account The initial account to grant all the tokens * @param minter_ The account with minting ability */ constructor(address account, address minter_) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); } /** * @notice Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "Tribe::setMinter: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "Tribe::mint: only the minter can mint"); require(dst != address(0), "Tribe::mint: cannot transfer to the zero address"); // mint the amount uint96 amount = safe96(rawAmount, "Tribe::mint: amount exceeds 96 bits"); uint96 safeSupply = safe96(totalSupply, "Tribe::mint: totalSupply exceeds 96 bits"); totalSupply = add96(safeSupply, amount, "Tribe::mint: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "Tribe::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Tribe::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Tribe::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Tribe::permit: invalid signature"); require(signatory == owner, "Tribe::permit: unauthorized"); require(now <= deadline, "Tribe::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Tribe::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Tribe::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Tribe::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Tribe::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Tribe::delegateBySig: invalid nonce"); // solhint-disable-next-line not-rely-on-time require(now <= expiry, "Tribe::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Tribe::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Tribe::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Tribe::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Tribe::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Tribe::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Tribe::_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, "Tribe::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Tribe::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } // File contracts/fei-protocol/core/Core.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title ICore implementation /// @author Fei Protocol contract Core is ICore, Permissions { IFei public override fei; IERC20 public override tribe; address public override genesisGroup; bool public override hasGenesisGroupCompleted; constructor() public { _setupGovernor(msg.sender); Fei _fei = new Fei(address(this)); fei = IFei(address(_fei)); Tribe _tribe = new Tribe(address(this), msg.sender); tribe = IERC20(address(_tribe)); } function setFei(address token) external override onlyGovernor { fei = IFei(token); emit FeiUpdate(token); } function setGenesisGroup(address _genesisGroup) external override onlyGovernor { genesisGroup = _genesisGroup; } function allocateTribe(address to, uint amount) external override onlyGovernor { IERC20 _tribe = tribe; require(_tribe.balanceOf(address(this)) > amount, "Core: Not enough Tribe"); _tribe.transfer(to, amount); emit TribeAllocation(to, amount); } function completeGenesisGroup() external override { require(!hasGenesisGroupCompleted, "Core: Genesis Group already complete"); require(msg.sender == genesisGroup, "Core: Caller is not Genesis Group"); hasGenesisGroupCompleted = true; // solhint-disable-next-line not-rely-on-time emit GenesisPeriodComplete(now); } } // File contracts/fei-protocol/dao/ITimelockedDelegator.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface ITribe is IERC20 { function delegate(address delegatee) external; } /// @title a timelock for TRIBE allowing for sub-delegation /// @author Fei Protocol /// @notice allows the timelocked TRIBE to be delegated by the beneficiary while locked interface ITimelockedDelegator { // ----------- Events ----------- event Delegate(address indexed _delegatee, uint _amount); event Undelegate(address indexed _delegatee, uint _amount); // ----------- Beneficiary only state changing api ----------- /// @notice delegate locked TRIBE to a delegatee /// @param delegatee the target address to delegate to /// @param amount the amount of TRIBE to delegate. Will increment existing delegated TRIBE function delegate(address delegatee, uint amount) external; /// @notice return delegated TRIBE to the timelock /// @param delegatee the target address to undelegate from /// @return the amount of TRIBE returned function undelegate(address delegatee) external returns(uint); // ----------- Getters ----------- /// @notice associated delegate proxy contract for a delegatee /// @param delegatee The delegatee /// @return the corresponding delegate proxy contract function delegateContract(address delegatee) external view returns(address); /// @notice associated delegated amount for a delegatee /// @param delegatee The delegatee /// @return uint amount of TRIBE delegated /// @dev Using as source of truth to prevent accounting errors by transferring to Delegate contracts function delegateAmount(address delegatee) external view returns(uint); /// @notice the total delegated amount of TRIBE function totalDelegated() external view returns(uint); /// @notice the TRIBE token contract function tribe() external view returns(ITribe); } // File contracts/fei-protocol/dao/Timelock.sol pragma solidity ^0.6.0; // Forked from Compound // See https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 1 hours; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returnData) = target.call{value: value}(callData); //solhint-disable avoid-call-value require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solhint-disable-next-line not-rely-on-time return block.timestamp; } } // File @openzeppelin/contracts/access/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/fei-protocol/utils/LinearTokenTimelock.sol pragma solidity ^0.6.0; // Inspired by OpenZeppelin TokenTimelock contract // Reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/TokenTimelock.sol contract LinearTokenTimelock is Timed { // ERC20 basic token contract being held IERC20 public lockedToken; // beneficiary of tokens after they are released address public beneficiary; address public pendingBeneficiary; uint public initialBalance; uint internal lastBalance; event Release(address indexed _beneficiary, uint _amount); event BeneficiaryUpdate(address indexed _beneficiary); event PendingBeneficiaryUpdate(address indexed _pendingBeneficiary); constructor (address _beneficiary, uint32 _duration) public Timed(_duration) { require(_duration != 0, "LinearTokenTimelock: duration is 0"); beneficiary = _beneficiary; _initTimed(); } // Prevents incoming LP tokens from messing up calculations modifier balanceCheck() { if (totalToken() > lastBalance) { uint delta = totalToken() - lastBalance; initialBalance += delta; } _; lastBalance = totalToken(); } modifier onlyBeneficiary() { require(msg.sender == beneficiary, "LinearTokenTimelock: Caller is not a beneficiary"); _; } function release() external onlyBeneficiary balanceCheck { uint amount = availableForRelease(); require(amount != 0, "LinearTokenTimelock: no tokens to release"); lockedToken.transfer(beneficiary, amount); emit Release(beneficiary, amount); } function totalToken() public view virtual returns(uint) { return lockedToken.balanceOf(address(this)); } function alreadyReleasedAmount() public view returns(uint) { return initialBalance - totalToken(); } function availableForRelease() public view returns(uint) { uint elapsed = timestamp(); uint _duration = duration; uint totalAvailable = initialBalance * elapsed / _duration; uint netAvailable = totalAvailable - alreadyReleasedAmount(); return netAvailable; } function setPendingBeneficiary(address _pendingBeneficiary) public onlyBeneficiary { pendingBeneficiary = _pendingBeneficiary; emit PendingBeneficiaryUpdate(_pendingBeneficiary); } function acceptBeneficiary() public virtual { _setBeneficiary(msg.sender); } function _setBeneficiary(address newBeneficiary) internal { require(newBeneficiary == pendingBeneficiary, "LinearTokenTimelock: Caller is not pending beneficiary"); beneficiary = newBeneficiary; emit BeneficiaryUpdate(newBeneficiary); pendingBeneficiary = address(0); } function setLockedToken(address tokenAddress) internal { lockedToken = IERC20(tokenAddress); } } // File contracts/fei-protocol/dao/TimelockedDelegator.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title a proxy delegate contract for TRIBE /// @author Fei Protocol contract Delegatee is Ownable { ITribe public tribe; /// @notice Delegatee constructor /// @param _delegatee the address to delegate TRIBE to /// @param _tribe the TRIBE token address constructor(address _delegatee, address _tribe) public { tribe = ITribe(_tribe); tribe.delegate(_delegatee); } /// @notice send TRIBE back to timelock and selfdestruct function withdraw() public onlyOwner { ITribe _tribe = tribe; uint balance = _tribe.balanceOf(address(this)); _tribe.transfer(owner(), balance); selfdestruct(payable(owner())); } } /// @title ITimelockedDelegator implementation /// @author Fei Protocol contract TimelockedDelegator is ITimelockedDelegator, LinearTokenTimelock { mapping (address => address) public override delegateContract; mapping (address => uint) public override delegateAmount; ITribe public override tribe; uint public override totalDelegated; /// @notice Delegatee constructor /// @param _tribe the TRIBE token address /// @param _beneficiary default delegate, admin, and timelock beneficiary /// @param _duration duration of the token timelock window constructor(address _tribe, address _beneficiary, uint32 _duration) public LinearTokenTimelock(_beneficiary, _duration) { tribe = ITribe(_tribe); tribe.delegate(_beneficiary); setLockedToken(_tribe); } function delegate(address delegatee, uint amount) public override onlyBeneficiary { require(amount <= tribeBalance(), "TimelockedDelegator: Not enough Tribe"); if (delegateContract[delegatee] != address(0)) { amount += undelegate(delegatee); } ITribe _tribe = tribe; address _delegateContract = address(new Delegatee(delegatee, address(_tribe))); delegateContract[delegatee] = _delegateContract; delegateAmount[delegatee] = amount; totalDelegated += amount; _tribe.transfer(_delegateContract, amount); emit Delegate(delegatee, amount); } function undelegate(address delegatee) public override onlyBeneficiary returns(uint) { address _delegateContract = delegateContract[delegatee]; require(_delegateContract != address(0), "TimelockedDelegator: Delegate contract nonexistent"); Delegatee(_delegateContract).withdraw(); uint amount = delegateAmount[delegatee]; totalDelegated -= amount; delegateContract[delegatee] = address(0); delegateAmount[delegatee] = 0; emit Undelegate(delegatee, amount); return amount; } /// @notice calculate total TRIBE held plus delegated /// @dev used by LinearTokenTimelock to determine the released amount function totalToken() public view override returns(uint256) { return tribeBalance() + totalDelegated; } /// @notice accept beneficiary role over timelocked TRIBE. Delegates all held (non-subdelegated) tribe to beneficiary function acceptBeneficiary() public override { _setBeneficiary(msg.sender); tribe.delegate(msg.sender); } function tribeBalance() internal view returns (uint256) { return tribe.balanceOf(address(this)); } } // File contracts/fei-protocol/genesis/IGenesisGroup.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Equal access to the first bonding curve transaction /// @author Fei Protocol interface IGenesisGroup { // ----------- Events ----------- event Purchase(address indexed _to, uint _value); event Redeem(address indexed _to, uint _amountIn, uint _amountFei, uint _amountTribe); event Commit(address indexed _from, address indexed _to, uint _amount); event Launch(uint _timestamp); // ----------- State changing API ----------- /// @notice allows for entry into the Genesis Group via ETH. Only callable during Genesis Period. /// @param to address to send FGEN Genesis tokens to /// @param value amount of ETH to deposit function purchase(address to, uint value) external payable; /// @notice redeem FGEN genesis tokens for FEI and TRIBE. Only callable post launch /// @param to address to send redeemed FEI and TRIBE to. function redeem(address to) external; /// @notice commit Genesis FEI to purchase TRIBE in DEX offering /// @param from address to source FGEN Genesis shares from /// @param to address to earn TRIBE and redeem post launch /// @param amount of FGEN Genesis shares to commit function commit(address from, address to, uint amount) external; /// @notice launch Fei Protocol. Callable once Genesis Period has ended or the max price has been reached function launch() external; // ----------- Getters ----------- /// @notice calculate amount of FEI and TRIBE received if the Genesis Group ended now. /// @param amountIn amount of FGEN held or equivalently amount of ETH purchasing with /// @param inclusive if true, assumes the `amountIn` is part of the existing FGEN supply. Set to false to simulate a new purchase. /// @return feiAmount the amount of FEI received by the user /// @return tribeAmount the amount of TRIBE received by the user function getAmountOut(uint amountIn, bool inclusive) external view returns (uint feiAmount, uint tribeAmount); /// @notice check whether GenesisGroup has reached max FEI price. Sufficient condition for launch function isAtMaxPrice() external view returns(bool); } // File contracts/fei-protocol/genesis/IDOInterface.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title an initial DeFi offering for the TRIBE token /// @author Fei Protocol interface IDOInterface { // ----------- Events ----------- event Deploy(uint _amountFei, uint _amountTribe); // ----------- Genesis Group only state changing API ----------- /// @notice deploys all held TRIBE on Uniswap at the given ratio /// @param feiRatio the exchange rate for FEI/TRIBE /// @dev the contract will mint any FEI necessary to do the listing. Assumes no existing LP function deploy(Decimal.D256 calldata feiRatio) external; /// @notice swaps Genesis Group FEI on Uniswap For TRIBE /// @param amountFei the amount of FEI to swap /// @return uint amount of TRIBE sent to Genesis Group function swapFei(uint amountFei) external returns(uint); } // File contracts/fei-protocol/pool/IPool.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title A fluid pool for earning a reward token with staked tokens /// @author Fei Protocol interface IPool { // ----------- Events ----------- event Claim(address indexed _from, address indexed _to, uint _amountReward); event Deposit(address indexed _from, address indexed _to, uint _amountStaked); event Withdraw(address indexed _from, address indexed _to, uint _amountStaked, uint _amountReward); // ----------- State changing API ----------- /// @notice collect redeemable rewards without unstaking /// @param from the account to claim for /// @param to the account to send rewards to /// @return the amount of reward claimed /// @dev redeeming on behalf of another account requires ERC-20 approval of the pool tokens function claim(address from, address to) external returns(uint); /// @notice deposit staked tokens /// @param to the account to deposit to /// @param amount the amount of staked to deposit /// @dev requires ERC-20 approval of stakedToken for the Pool contract function deposit(address to, uint amount) external; /// @notice claim all rewards and withdraw stakedToken /// @param to the account to send withdrawn tokens to /// @return amountStaked the amount of stakedToken withdrawn /// @return amountReward the amount of rewardToken received function withdraw(address to) external returns(uint amountStaked, uint amountReward); /// @notice initializes the pool start time. Only callable once function init() external; // ----------- Getters ----------- /// @notice the ERC20 reward token /// @return the IERC20 implementation address function rewardToken() external view returns(IERC20); /// @notice the total amount of rewards distributed by the contract over entire period /// @return the total, including currently held and previously claimed rewards function totalReward() external view returns (uint); /// @notice the amount of rewards currently redeemable by an account /// @param account the potentially redeeming account /// @return amountReward the amount of reward tokens /// @return amountPool the amount of redeemable pool tokens function redeemableReward(address account) external view returns(uint amountReward, uint amountPool); /// @notice the total amount of rewards owned by contract and unlocked for release /// @return the total function releasedReward() external view returns (uint); /// @notice the total amount of rewards owned by contract and locked /// @return the total function unreleasedReward() external view returns (uint); /// @notice the total balance of rewards owned by contract, locked or unlocked /// @return the total function rewardBalance() external view returns (uint); /// @notice the total amount of rewards previously claimed /// @return the total function claimedRewards() external view returns(uint128); /// @notice the ERC20 staked token /// @return the IERC20 implementation address function stakedToken() external view returns(IERC20); /// @notice the total amount of staked tokens in the contract /// @return the total function totalStaked() external view returns(uint128); /// @notice the staked balance of a given account /// @param account the user account /// @return the total staked function stakedBalance(address account) external view returns(uint); } // File contracts/fei-protocol/oracle/IBondingCurveOracle.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title bonding curve oracle interface for Fei Protocol /// @author Fei Protocol /// @notice peg is to be the current bonding curve price if pre-Scale interface IBondingCurveOracle is IOracle { // ----------- Genesis Group only state changing API ----------- /// @notice initializes the oracle with an initial peg price /// @param initialPeg a peg denominated in Dollars per X /// @dev divides the initial peg by the uniswap oracle price to get initialPrice. And kicks off thawing period function init(Decimal.D256 calldata initialPeg) external; // ----------- Getters ----------- /// @notice the referenced uniswap oracle price function uniswapOracle() external returns(IOracle); /// @notice the referenced bonding curve function bondingCurve() external returns(IBondingCurve); } // File contracts/fei-protocol/genesis/GenesisGroup.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title IGenesisGroup implementation /// @author Fei Protocol contract GenesisGroup is IGenesisGroup, CoreRef, ERC20, ERC20Burnable, Timed { using Decimal for Decimal.D256; IBondingCurve private bondingcurve; IBondingCurveOracle private bondingCurveOracle; IPool private pool; IDOInterface private ido; uint private exchangeRateDiscount; mapping(address => uint) public committedFGEN; uint public totalCommittedFGEN; uint public totalCommittedTribe; /// @notice a cap on the genesis group purchase price Decimal.D256 public maxGenesisPrice; /// @notice GenesisGroup constructor /// @param _core Fei Core address to reference /// @param _bondingcurve Bonding curve address for purchase /// @param _ido IDO contract to deploy /// @param _oracle Bonding curve oracle /// @param _pool Staking Pool /// @param _duration duration of the Genesis Period /// @param _maxPriceBPs max price of FEI allowed in Genesis Group in dollar terms /// @param _exchangeRateDiscount a divisor on the FEI/TRIBE ratio at Genesis to deploy to the IDO constructor( address _core, address _bondingcurve, address _ido, address _oracle, address _pool, uint32 _duration, uint _maxPriceBPs, uint _exchangeRateDiscount ) public CoreRef(_core) ERC20("Fei Genesis Group", "FGEN") Timed(_duration) { bondingcurve = IBondingCurve(_bondingcurve); exchangeRateDiscount = _exchangeRateDiscount; ido = IDOInterface(_ido); fei().approve(_ido, uint(-1)); pool = IPool(_pool); bondingCurveOracle = IBondingCurveOracle(_oracle); _initTimed(); maxGenesisPrice = Decimal.ratio(_maxPriceBPs, 10000); } modifier onlyGenesisPeriod() { require(!isTimeEnded(), "GenesisGroup: Not in Genesis Period"); _; } function purchase(address to, uint value) external override payable onlyGenesisPeriod { require(msg.value == value, "GenesisGroup: value mismatch"); require(value != 0, "GenesisGroup: no value sent"); _mint(to, value); emit Purchase(to, value); } function commit(address from, address to, uint amount) external override onlyGenesisPeriod { burnFrom(from, amount); committedFGEN[to] = amount; totalCommittedFGEN += amount; emit Commit(from, to, amount); } function redeem(address to) external override { (uint feiAmount, uint genesisTribe, uint idoTribe) = getAmountsToRedeem(to); uint tribeAmount = genesisTribe + idoTribe; require(tribeAmount != 0, "GenesisGroup: No redeemable TRIBE"); uint amountIn = balanceOf(to); burnFrom(to, amountIn); uint committed = committedFGEN[to]; committedFGEN[to] = 0; totalCommittedFGEN -= committed; totalCommittedTribe -= idoTribe; if (feiAmount != 0) { fei().transfer(to, feiAmount); } tribe().transfer(to, tribeAmount); emit Redeem(to, amountIn, feiAmount, tribeAmount); } function getAmountsToRedeem(address to) public view postGenesis returns (uint feiAmount, uint genesisTribe, uint idoTribe) { uint userFGEN = balanceOf(to); uint userCommittedFGEN = committedFGEN[to]; uint circulatingFGEN = totalSupply(); uint totalFGEN = circulatingFGEN + totalCommittedFGEN; // subtract purchased TRIBE amount uint totalGenesisTribe = tribeBalance() - totalCommittedTribe; if (circulatingFGEN != 0) { feiAmount = feiBalance() * userFGEN / circulatingFGEN; } if (totalFGEN != 0) { genesisTribe = totalGenesisTribe * (userFGEN + userCommittedFGEN) / totalFGEN; } if (totalCommittedFGEN != 0) { idoTribe = totalCommittedTribe * userCommittedFGEN / totalCommittedFGEN; } return (feiAmount, genesisTribe, idoTribe); } function launch() external override { require(isTimeEnded() || isAtMaxPrice(), "GenesisGroup: Still in Genesis Period"); core().completeGenesisGroup(); address genesisGroup = address(this); uint balance = genesisGroup.balance; bondingCurveOracle.init(bondingcurve.getAveragePrice(balance)); bondingcurve.purchase{value: balance}(genesisGroup, balance); bondingcurve.allocate(); pool.init(); ido.deploy(_feiTribeExchangeRate()); uint amountFei = feiBalance() * totalCommittedFGEN / (totalSupply() + totalCommittedFGEN); if (amountFei != 0) { totalCommittedTribe = ido.swapFei(amountFei); } // solhint-disable-next-line not-rely-on-time emit Launch(now); } // Add a backdoor out of Genesis in case of brick function emergencyExit(address from, address to) external { require(now > (startTime + duration + 3 days), "GenesisGroup: Not in exit window"); uint amountFGEN = balanceOf(from); uint total = amountFGEN + committedFGEN[from]; require(total != 0, "GenesisGroup: No FGEN or committed balance"); require(address(this).balance >= total, "GenesisGroup: Not enough ETH to redeem"); require(msg.sender == from || allowance(from, msg.sender) >= total, "GenesisGroup: Not approved for emergency withdrawal"); burnFrom(from, amountFGEN); committedFGEN[from] = 0; payable(to).transfer(total); } function getAmountOut( uint amountIn, bool inclusive ) public view override returns (uint feiAmount, uint tribeAmount) { uint totalIn = totalSupply(); if (!inclusive) { totalIn += amountIn; } require(amountIn <= totalIn, "GenesisGroup: Not enough supply"); uint totalFei = bondingcurve.getAmountOut(totalIn); uint totalTribe = tribeBalance(); return (totalFei * amountIn / totalIn, totalTribe * amountIn / totalIn); } function isAtMaxPrice() public view override returns(bool) { uint balance = address(this).balance; require(balance != 0, "GenesisGroup: No balance"); return bondingcurve.getAveragePrice(balance).greaterThanOrEqualTo(maxGenesisPrice); } function burnFrom(address account, uint amount) public override { // Sender doesn't need approval if (msg.sender == account) { increaseAllowance(account, amount); } super.burnFrom(account, amount); } function _feiTribeExchangeRate() public view returns (Decimal.D256 memory) { return Decimal.ratio(feiBalance(), tribeBalance()).div(exchangeRateDiscount); } } // File @uniswap/v2-core/contracts/interfaces/[email protected] 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; } // File @uniswap/v2-periphery/contracts/libraries/[email protected] pragma solidity =0.6.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { 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'); } } // File @uniswap/v2-periphery/contracts/libraries/[email protected] pragma solidity >=0.5.0; library UniswapV2Library { using SafeMath for uint; // 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) internal pure returns (address pair) { (address token0, address token1) = sortTokens(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 getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).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(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint 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(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint 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(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { 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) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { 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) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File @uniswap/v2-periphery/contracts/interfaces/[email protected] 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); } // File @uniswap/v2-periphery/contracts/interfaces/[email protected] pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File contracts/fei-protocol/refs/IUniRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title A Uniswap Reference contract /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Uniswap /// @dev the uniswap pair should be FEI and another asset interface IUniRef { // ----------- Events ----------- event PairUpdate(address indexed _pair); // ----------- Governor only state changing api ----------- /// @notice set the new pair contract /// @param _pair the new pair /// @dev also approves the router for the new pair token and underlying token function setPair(address _pair) external; // ----------- Getters ----------- /// @notice the Uniswap router contract /// @return the IUniswapV2Router02 router implementation address function router() external view returns(IUniswapV2Router02); /// @notice the referenced Uniswap pair contract /// @return the IUniswapV2Pair router implementation address function pair() external view returns(IUniswapV2Pair); /// @notice the address of the non-fei underlying token /// @return the token address function token() external view returns(address); /// @notice pair reserves with fei listed first /// @dev uses the max of pair fei balance and fei reserves. Mitigates attack vectors which manipulate the pair balance function getReserves() external view returns (uint feiReserves, uint tokenReserves); /// @notice amount of pair liquidity owned by this contract /// @return amount of LP tokens function liquidityOwned() external view returns (uint); } // File contracts/fei-protocol/refs/UniRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title UniRef abstract implementation contract /// @author Fei Protocol abstract contract UniRef is IUniRef, OracleRef { using Decimal for Decimal.D256; using Babylonian for uint; IUniswapV2Router02 public override router; IUniswapV2Pair public override pair; /// @notice UniRef constructor /// @param _core Fei Core to reference /// @param _pair Uniswap pair to reference /// @param _router Uniswap Router to reference /// @param _oracle oracle to reference constructor(address _core, address _pair, address _router, address _oracle) public OracleRef(_core, _oracle) { setupPair(_pair); router = IUniswapV2Router02(_router); approveToken(address(fei())); approveToken(token()); approveToken(_pair); } function setPair(address _pair) external override onlyGovernor { setupPair(_pair); approveToken(token()); approveToken(_pair); } function token() public override view returns (address) { address token0 = pair.token0(); if (address(fei()) == token0) { return pair.token1(); } return token0; } function getReserves() public override view returns (uint feiReserves, uint tokenReserves) { address token0 = pair.token0(); (uint reserve0, uint reserve1,) = pair.getReserves(); (feiReserves, tokenReserves) = address(fei()) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); uint feiBalance = fei().balanceOf(address(pair)); if(feiBalance > feiReserves) { feiReserves = feiBalance; } return (feiReserves, tokenReserves); } function liquidityOwned() public override view returns (uint) { return pair.balanceOf(address(this)); } /// @notice ratio of all pair liquidity owned by this contract function ratioOwned() internal view returns (Decimal.D256 memory) { uint balance = liquidityOwned(); uint total = pair.totalSupply(); return Decimal.ratio(balance, total); } /// @notice returns true if price is below the peg /// @dev counterintuitively checks if peg < price because price is reported as FEI per X function isBelowPeg(Decimal.D256 memory peg) internal view returns (bool) { (Decimal.D256 memory price,,) = getUniswapPrice(); return peg.lessThan(price); } /// @notice approves a token for the router function approveToken(address _token) internal { IERC20(_token).approve(address(router), uint(-1)); } function setupPair(address _pair) internal { pair = IUniswapV2Pair(_pair); emit PairUpdate(_pair); } function isPair(address account) internal view returns(bool) { return address(pair) == account; } /// @notice utility for calculating absolute distance from peg based on reserves /// @param reserveTarget pair reserves of the asset desired to trade with /// @param reserveOther pair reserves of the non-traded asset /// @param peg the target peg reported as Target per Other function getAmountToPeg( uint reserveTarget, uint reserveOther, Decimal.D256 memory peg ) internal pure returns (uint) { uint radicand = peg.mul(reserveTarget).mul(reserveOther).asUint256(); uint root = radicand.sqrt(); if (root > reserveTarget) { return root - reserveTarget; } return reserveTarget - root; } /// @notice calculate amount of Fei needed to trade back to the peg function getAmountToPegFei() internal view returns (uint) { (uint feiReserves, uint tokenReserves) = getReserves(); return getAmountToPeg(feiReserves, tokenReserves, peg()); } /// @notice calculate amount of the not Fei token needed to trade back to the peg function getAmountToPegOther() internal view returns (uint) { (uint feiReserves, uint tokenReserves) = getReserves(); return getAmountToPeg(tokenReserves, feiReserves, invert(peg())); } /// @notice get uniswap price and reserves /// @return price reported as Fei per X /// @return reserveFei fei reserves /// @return reserveOther non-fei reserves function getUniswapPrice() internal view returns( Decimal.D256 memory, uint reserveFei, uint reserveOther ) { (reserveFei, reserveOther) = getReserves(); return (Decimal.ratio(reserveFei, reserveOther), reserveFei, reserveOther); } /// @notice get final uniswap price after hypothetical FEI trade /// @param amountFei a signed integer representing FEI trade. Positive=sell, negative=buy /// @param reserveFei fei reserves /// @param reserveOther non-fei reserves function getFinalPrice( int256 amountFei, uint reserveFei, uint reserveOther ) internal pure returns (Decimal.D256 memory) { uint k = reserveFei * reserveOther; uint adjustedReserveFei = uint(int256(reserveFei) + amountFei); uint adjustedReserveOther = k / adjustedReserveFei; return Decimal.ratio(adjustedReserveFei, adjustedReserveOther); // alt: adjustedReserveFei^2 / k } /// @notice return the percent distance from peg before and after a hypothetical trade /// @param amountIn a signed amount of FEI to be traded. Positive=sell, negative=buy /// @return initialDeviation the percent distance from peg before trade /// @return finalDeviation the percent distance from peg after hypothetical trade /// @dev deviations will return Decimal.zero() if above peg function getPriceDeviations(int256 amountIn) internal view returns ( Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ) { (Decimal.D256 memory price, uint reserveFei, uint reserveOther) = getUniswapPrice(); initialDeviation = calculateDeviation(price, peg()); Decimal.D256 memory finalPrice = getFinalPrice(amountIn, reserveFei, reserveOther); finalDeviation = calculateDeviation(finalPrice, peg()); return (initialDeviation, finalDeviation); } /// @notice return current percent distance from peg /// @dev will return Decimal.zero() if above peg function getDistanceToPeg() internal view returns(Decimal.D256 memory distance) { (Decimal.D256 memory price, , ) = getUniswapPrice(); return calculateDeviation(price, peg()); } /// @notice get deviation from peg as a percent given price /// @dev will return Decimal.zero() if above peg function calculateDeviation( Decimal.D256 memory price, Decimal.D256 memory peg ) internal pure returns (Decimal.D256 memory) { // If price <= peg, then FEI is more expensive and above peg // In this case we can just return zero for deviation if (price.lessThanOrEqualTo(peg)) { return Decimal.zero(); } Decimal.D256 memory delta = price.sub(peg, "UniRef: price exceeds peg"); // Should never error return delta.div(peg); } } // File contracts/fei-protocol/genesis/IDO.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title IDOInterface implementation /// @author Fei Protocol contract IDO is IDOInterface, UniRef, LinearTokenTimelock { /// @notice IDO constructor /// @param _core Fei Core address to reference /// @param _beneficiary the beneficiary to vest LP shares /// @param _duration the duration of LP share vesting /// @param _pair the Uniswap pair contract of the IDO /// @param _router the Uniswap router contract constructor( address _core, address _beneficiary, uint32 _duration, address _pair, address _router ) public UniRef(_core, _pair, _router, address(0)) // no oracle needed LinearTokenTimelock(_beneficiary, _duration) { setLockedToken(_pair); } function deploy(Decimal.D256 calldata feiRatio) external override onlyGenesisGroup { uint tribeAmount = tribeBalance(); uint feiAmount = feiRatio.mul(tribeAmount).asUint256(); _mintFei(feiAmount); router.addLiquidity( address(tribe()), address(fei()), tribeAmount, feiAmount, tribeAmount, feiAmount, address(this), uint(-1) ); emit Deploy(feiAmount, tribeAmount); } function swapFei(uint amountFei) external override onlyGenesisGroup returns(uint) { (uint feiReserves, uint tribeReserves) = getReserves(); uint amountOut = UniswapV2Library.getAmountOut(amountFei, feiReserves, tribeReserves); fei().transferFrom(msg.sender, address(pair), amountFei); (uint amount0Out, uint amount1Out) = pair.token0() == address(fei()) ? (uint(0), amountOut) : (amountOut, uint(0)); pair.swap(amount0Out, amount1Out, msg.sender, new bytes(0)); return amountOut; } } // File contracts/fei-protocol/mock/IMockUniswapV2PairLiquidity.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface IMockUniswapV2PairLiquidity is IUniswapV2Pair { function burnEth(address to, Decimal.D256 calldata ratio) external returns(uint256 amountEth, uint256 amount1); function mintAmount(address to, uint256 _liquidity) external payable; function setReserves(uint112 newReserve0, uint112 newReserve1) external; } // File contracts/fei-protocol/mock/MockBondingCurve.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockBondingCurve { bool public atScale; bool public allocated; Decimal.D256 public getCurrentPrice; constructor(bool _atScale, uint256 price) public { setScale(_atScale); setCurrentPrice(price); } function setScale(bool _atScale) public { atScale = _atScale; } function setCurrentPrice(uint256 price) public { getCurrentPrice = Decimal.ratio(price, 100); } function allocate() public payable { allocated = true; } function purchase(address to, uint amount) public payable returns (uint256 amountOut) { return 1; } function getAmountOut(uint amount) public view returns(uint) { return 10 * amount; } function getAveragePrice(uint256 amountIn) public view returns (Decimal.D256 memory) { return getCurrentPrice; } } // File contracts/fei-protocol/mock/MockCoreRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockCoreRef is CoreRef { constructor(address core) CoreRef(core) public {} function testMinter() public view onlyMinter {} function testBurner() public view onlyBurner {} function testPCVController() public view onlyPCVController {} function testGovernor() public view onlyGovernor {} function testPostGenesis() public view postGenesis {} } // File contracts/fei-protocol/mock/MockERC20.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockERC20 is ERC20, ERC20Burnable { constructor() ERC20("MockToken", "MCT") public {} function mint(address account, uint256 amount) public returns (bool) { _mint(account, amount); return true; } } // File contracts/fei-protocol/mock/MockEthPCVDeposit.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockEthPCVDeposit is IPCVDeposit { address payable beneficiary; uint256 total = 0; constructor(address payable _beneficiary) public { beneficiary = _beneficiary; } function deposit(uint256 amount) external override payable { require(amount == msg.value, "MockEthPCVDeposit: Sent value does not equal input"); beneficiary.transfer(amount); total += amount; } function withdraw(address to, uint256 amount) external override { require(address(this).balance >= amount, "MockEthPCVDeposit: Not enough value held"); total -= amount; payable(to).transfer(amount); } function totalValue() external view override returns(uint256) { return total; } } // File contracts/fei-protocol/mock/MockEthUniswapPCVDeposit.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockEthUniswapPCVDeposit is MockEthPCVDeposit { address public pair; constructor(address _pair) MockEthPCVDeposit(payable(this)) public { pair = _pair; } fallback() external payable { } } // File contracts/fei-protocol/mock/MockIDO.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockIDO { Decimal.D256 public ratio = Decimal.zero(); IERC20 public tribe; uint multiplier; constructor(address _tribe, uint _multiplier) public { tribe = IERC20(_tribe); multiplier = _multiplier; } function deploy(Decimal.D256 memory feiRatio) public { ratio = feiRatio; } function swapFei(uint amount) public returns (uint amountOut) { amountOut = amount * multiplier; tribe.transfer(msg.sender, amountOut); return amountOut; } } // File contracts/fei-protocol/mock/MockIncentive.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockIncentive is IIncentive, CoreRef { constructor(address core) CoreRef(core) public {} uint256 constant private INCENTIVE = 100; function incentivize( address sender, address receiver, address spender, uint256 amountIn ) public override { fei().mint(sender, INCENTIVE); } } // File contracts/fei-protocol/mock/MockOracle.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockOracle is IOracle { using Decimal for Decimal.D256; // fixed exchange ratio uint256 _usdPerEth; bool public override killSwitch; bool public updated; bool public valid = true; constructor(uint256 usdPerEth) public { _usdPerEth = usdPerEth; } function update() public override returns (bool) { updated = true; return true; } function read() public view override returns (Decimal.D256 memory, bool) { Decimal.D256 memory price = Decimal.from(_usdPerEth); return (price, valid); } function setValid(bool isValid) public { valid = isValid; } function setExchangeRate(uint256 usdPerEth) public { _usdPerEth = usdPerEth; } function setKillSwitch(bool _killSwitch) public override { killSwitch = _killSwitch; } } // File contracts/fei-protocol/mock/MockOrchestrator.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockBCO { Decimal.D256 public initPrice; function init(Decimal.D256 memory price) public { initPrice = price; } } contract MockPool { function init() public {} } contract MockOrchestrator { address public bondingCurveOracle; address public pool; constructor() public { bondingCurveOracle = address(new MockBCO()); pool = address(new MockPool()); } function launchGovernance() external {} } // File contracts/fei-protocol/mock/MockRouter.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockRouter { using SafeMath for uint256; using Decimal for Decimal.D256; IMockUniswapV2PairLiquidity private PAIR; address public WETH; constructor(address pair) public { PAIR = IMockUniswapV2PairLiquidity(pair); } uint256 private totalLiquidity; uint256 private constant LIQUIDITY_INCREMENT = 10000; function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity) { address pair = address(PAIR); amountToken = amountTokenDesired; amountETH = msg.value; liquidity = LIQUIDITY_INCREMENT; (uint112 reserves0, uint112 reserves1, ) = PAIR.getReserves(); IERC20(token).transferFrom(to, pair, amountToken); PAIR.mintAmount{value: amountETH}(to, LIQUIDITY_INCREMENT); totalLiquidity += LIQUIDITY_INCREMENT; uint112 newReserve0 = uint112(reserves0) + uint112(amountETH); uint112 newReserve1 = uint112(reserves1) + uint112(amountToken); PAIR.setReserves(newReserve0, newReserve1); } function addLiquidity( address token0, address token1, uint amountToken0Desired, uint amountToken1Desired, uint amountToken0Min, uint amountToken1Min, address to, uint deadline ) external returns (uint amountToken0, uint amountToken1, uint liquidity) { address pair = address(PAIR); liquidity = LIQUIDITY_INCREMENT; IERC20(token0).transferFrom(to, pair, amountToken0Desired); IERC20(token1).transferFrom(to, pair, amountToken1Desired); PAIR.mintAmount(to, LIQUIDITY_INCREMENT); } function setWETH(address weth) public { WETH = weth; } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH) { Decimal.D256 memory percentWithdrawal = Decimal.ratio(liquidity, totalLiquidity); Decimal.D256 memory ratio = ratioOwned(to); (amountETH, amountToken) = PAIR.burnEth(to, ratio.mul(percentWithdrawal)); (uint112 reserves0, uint112 reserves1, ) = PAIR.getReserves(); uint112 newReserve0 = uint112(reserves0) - uint112(amountETH); uint112 newReserve1 = uint112(reserves1) - uint112(amountToken); PAIR.setReserves(newReserve0, newReserve1); transferLiquidity(liquidity); } function transferLiquidity(uint liquidity) internal { PAIR.transferFrom(msg.sender, address(PAIR), liquidity); // send liquidity to pair } function ratioOwned(address to) public view returns (Decimal.D256 memory) { uint256 balance = PAIR.balanceOf(to); uint256 total = PAIR.totalSupply(); return Decimal.ratio(balance, total); } } // File contracts/fei-protocol/mock/MockSettableCore.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockSettableCore is Core { // anyone can set any role function isGovernor(address _address) public view override returns (bool) { return true; } } // File contracts/fei-protocol/mock/MockTribe.sol pragma solidity ^0.6.0; contract MockTribe is MockERC20 { function delegate(address account) external {} } // File contracts/fei-protocol/mock/MockUniswapIncentive.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockUniswapIncentive is MockIncentive { constructor(address core) MockIncentive(core) public {} bool isParity = false; bool isExempt = false; function isIncentiveParity() external view returns (bool) { return isParity; } function setIncentiveParity(bool _isParity) public { isParity = _isParity; } function isExemptAddress(address account) public returns (bool) { return isExempt; } function setExempt(bool exempt) public { isExempt = exempt; } function updateOracle() external returns(bool) { return true; } function setExemptAddress(address account, bool isExempt) external {} function getBuyIncentive(uint amount) external returns(uint, uint32 weight, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ) { return (amount * 10 / 100, weight, initialDeviation, finalDeviation); } function getSellPenalty(uint amount) external returns(uint, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation) { return (amount * 10 / 100, initialDeviation, finalDeviation); } } // File @uniswap/lib/contracts/libraries/[email protected] // 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); } } // File @uniswap/lib/contracts/libraries/[email protected] // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; library BitMath { // returns the 0 indexed position of the most significant bit of the input x // s.t. x >= 2**msb and x < 2**(msb+1) function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } // returns the 0 indexed position of the least significant bit of the input x // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0) // i.e. the bit at the index is set and the mask of all lower bits is 0 function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } // File @uniswap/lib/contracts/libraries/[email protected] // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // 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 public constant RESOLUTION = 112; uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112 uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224 uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // 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 uint, 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); } // multiply a UQ112x112 by an int and decode, returning an int // reverts on overflow function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); } // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 // lossy function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 // partial products uint224 upper = uint224(upper_self) * upper_other; // * 2^0 uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 // so the bit shift does not overflow require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow'); // this cannot exceed 256 bits, all values are 224 bits uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); // so the cast does not overflow require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow'); return uq112x112(uint224(sum)); } // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // can be lossy function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); 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)); } } // take the reciprocal of a UQ112x112 // reverts on overflow // lossy function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero'); require(self._x != 1, 'FixedPoint::reciprocal: overflow'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // File contracts/fei-protocol/mock/MockUniswapV2PairLiquidity.sol /* Copyright 2020 Empty Set Squad <[email protected]> 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.0; pragma experimental ABIEncoderV2; contract MockUniswapV2PairLiquidity is IUniswapV2Pair { using SafeMath for uint256; using Decimal for Decimal.D256; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint256 private liquidity; address public override token0; address public override token1; constructor(address _token0, address _token1) public { token0 = _token0; token1 = _token1; } function getReserves() external view override returns (uint112, uint112, uint32) { return (reserve0, reserve1, 0); } function mint(address to) public override returns (uint) { _mint(to, liquidity); return liquidity; } function mintAmount(address to, uint256 _liquidity) public payable { _mint(to, _liquidity); } function set(uint112 newReserve0, uint112 newReserve1, uint256 newLiquidity) external payable { reserve0 = newReserve0; reserve1 = newReserve1; liquidity = newLiquidity; mint(msg.sender); } function setReserves(uint112 newReserve0, uint112 newReserve1) external { reserve0 = newReserve0; reserve1 = newReserve1; } function faucet(address account, uint256 amount) external returns (bool) { _mint(account, amount); return true; } function burnEth(address to, Decimal.D256 memory ratio) public returns(uint256 amountEth, uint256 amount1) { uint256 balanceEth = address(this).balance; amountEth = ratio.mul(balanceEth).asUint256(); payable(to).transfer(amountEth); uint256 balance1 = reserve1; amount1 = ratio.mul(balance1).asUint256(); IERC20(token1).transfer(to, amount1); } function withdrawFei(address to, uint256 amount) public { IERC20(token1).transfer(to, amount); } function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external override { // No - op; } /** * Should not use */ function name() external pure override returns (string memory) { return "Uniswap V2"; } function symbol() external pure override returns (string memory) { return "UNI-V2"; } function decimals() external pure override returns (uint8) { return 18; } function DOMAIN_SEPARATOR() external view override returns (bytes32) { revert("Should not use"); } function PERMIT_TYPEHASH() external pure override returns (bytes32) { revert("Should not use"); } function nonces(address owner) external view override returns (uint) { revert("Should not use"); } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { revert("Should not use"); } function MINIMUM_LIQUIDITY() external pure override returns (uint) { revert("Should not use"); } function factory() external view override returns (address) { revert("Should not use"); } function price0CumulativeLast() external view override returns (uint) { revert("Should not use"); } function price1CumulativeLast() external view override returns (uint) { revert("Should not use"); } function kLast() external view override returns (uint) { revert("Should not use"); } function skim(address to) external override { revert("Should not use"); } function sync() external override { revert("Should not use"); } function burn(address to) external override returns (uint amount0, uint amount1) { revert("Should not use"); } function initialize(address, address) external override { revert("Should not use"); } // @openzeppelin/contracts/token/ERC20/ERC20.sol mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override 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 override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public 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 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); _approve(sender, msg.sender, _allowances[sender][msg.sender].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(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, "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, msg.sender, _allowances[account][msg.sender].sub(amount, "ERC20: burn amount exceeds allowance")); } } // File contracts/fei-protocol/mock/MockUniswapV2PairTrade.sol pragma solidity ^0.6.0; contract MockUniswapV2PairTrade { uint public price0CumulativeLast; uint public price1CumulativeLast; uint112 public reserve0; uint112 public reserve1; uint32 public blockTimestampLast; constructor( uint _price0CumulativeLast, uint _price1CumulativeLast, uint32 _blockTimestampLast, uint112 r0, uint112 r1 ) public { set(_price0CumulativeLast, _price1CumulativeLast, _blockTimestampLast); setReserves(r0, r1); } function getReserves() public view returns(uint112, uint112, uint32) { return (reserve0, reserve1, blockTimestampLast); } function simulateTrade(uint112 newReserve0, uint112 newReserve1, uint32 blockTimestamp) external { uint32 timeElapsed = blockTimestamp - blockTimestampLast; if (timeElapsed > 0 && reserve0 != 0 && reserve1 != 0) { price0CumulativeLast += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; price1CumulativeLast += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } reserve0 = newReserve0; reserve1 = newReserve1; blockTimestampLast = blockTimestamp; } function set(uint _price0CumulativeLast, uint _price1CumulativeLast, uint32 _blockTimestampLast) public { price0CumulativeLast = _price0CumulativeLast; price1CumulativeLast = _price1CumulativeLast; blockTimestampLast = _blockTimestampLast; } function setReserves(uint112 r0, uint112 r1) public { reserve0 = r0; reserve1 = r1; } } // File contracts/fei-protocol/mock/MockWeth.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockWeth is MockERC20 { constructor() public {} function deposit() external payable { mint(msg.sender, msg.value); } function withdraw(uint amount) external payable { _burn(msg.sender, amount); _msgSender().transfer(amount); } } // File contracts/fei-protocol/mock/RootsWrapper.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract RootsWrapper { using Roots for uint; function cubeRoot(uint x) public pure returns (uint) { return x.cubeRoot(); } function twoThirdsRoot(uint x) public pure returns (uint) { return x.twoThirdsRoot(); } function sqrt(uint x) public pure returns (uint) { return x.sqrt(); } } // File contracts/fei-protocol/oracle/BondingCurveOracle.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title IBondingCurveOracle implementation contract /// @author Fei Protocol /// @notice includes "thawing" on the initial purchase price at genesis. Time weights price from initial to true peg over a window. contract BondingCurveOracle is IBondingCurveOracle, CoreRef, Timed { using Decimal for Decimal.D256; IOracle public override uniswapOracle; IBondingCurve public override bondingCurve; bool public override killSwitch = true; /// @notice the price in dollars at initialization /// @dev this price will "thaw" to the peg price over `duration` window Decimal.D256 public initialPrice; event KillSwitchUpdate(bool _killSwitch); /// @notice BondingCurveOracle constructor /// @param _core Fei Core to reference /// @param _oracle Uniswap Oracle to report from /// @param _bondingCurve Bonding curve to report from /// @param _duration price thawing duration constructor( address _core, address _oracle, address _bondingCurve, uint32 _duration ) public CoreRef(_core) Timed(_duration) { uniswapOracle = IOracle(_oracle); bondingCurve = IBondingCurve(_bondingCurve); } function update() external override returns (bool) { return uniswapOracle.update(); } function read() external view override returns (Decimal.D256 memory, bool) { if (killSwitch) { return (Decimal.zero(), false); } (Decimal.D256 memory peg, bool valid) = getOracleValue(); return (thaw(peg), valid); } function setKillSwitch(bool _killSwitch) external override onlyGovernor { killSwitch = _killSwitch; emit KillSwitchUpdate(_killSwitch); } function init(Decimal.D256 memory _initialPrice) public override onlyGenesisGroup { killSwitch = false; initialPrice = _initialPrice; _initTimed(); } function thaw(Decimal.D256 memory peg) internal view returns (Decimal.D256 memory) { if (isTimeEnded()) { return peg; } uint t = uint(timestamp()); uint remaining = uint(remainingTime()); uint d = uint(duration); (Decimal.D256 memory uniswapPeg,) = uniswapOracle.read(); Decimal.D256 memory price = uniswapPeg.div(peg); Decimal.D256 memory weightedPrice = initialPrice.mul(remaining).add(price.mul(t)).div(d); return uniswapPeg.div(weightedPrice); } function getOracleValue() internal view returns(Decimal.D256 memory, bool) { if (bondingCurve.atScale()) { return uniswapOracle.read(); } return (bondingCurve.getCurrentPrice(), true); } } // File contracts/fei-protocol/oracle/IUniswapOracle.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Uniswap oracle interface for Fei Protocol /// @author Fei Protocol /// @notice maintains the TWAP of a uniswap pair contract over a specified duration interface IUniswapOracle is IOracle { // ----------- Events ----------- event DurationUpdate(uint32 _duration); // ----------- Governor only state changing API ----------- /// @notice set a new duration for the TWAP window function setDuration(uint32 _duration) external; // ----------- Getters ----------- /// @notice the previous timestamp of the oracle snapshot function priorTimestamp() external returns(uint32); /// @notice the previous cumulative price of the oracle snapshot function priorCumulative() external returns(uint); /// @notice the window over which the initial price will "thaw" to the true peg price function duration() external returns(uint32); /// @notice the referenced uniswap pair contract function pair() external returns(IUniswapV2Pair); } // File @uniswap/v2-periphery/contracts/libraries/[email protected] pragma solidity >=0.5.0; // 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 currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // File contracts/fei-protocol/oracle/UniswapOracle.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // Referencing Uniswap Example Simple Oracle // https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol /// @title IUniswapOracle implementation contract /// @author Fei Protocol contract UniswapOracle is IUniswapOracle, CoreRef { using Decimal for Decimal.D256; IUniswapV2Pair public override pair; bool private isPrice0; uint public override priorCumulative; uint32 public override priorTimestamp; Decimal.D256 private twap = Decimal.zero(); uint32 public override duration; bool public override killSwitch; /// @notice UniswapOracle constructor /// @param _core Fei Core for reference /// @param _pair Uniswap Pair to provide TWAP /// @param _duration TWAP duration /// @param _isPrice0 flag for using token0 or token1 for cumulative on Uniswap constructor( address _core, address _pair, uint32 _duration, bool _isPrice0 ) public CoreRef(_core) { pair = IUniswapV2Pair(_pair); // Relative to USD per ETH price isPrice0 = _isPrice0; duration = _duration; _init(); } function update() external override returns (bool) { (uint price0Cumulative, uint price1Cumulative, uint32 currentTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 deltaTimestamp = currentTimestamp - priorTimestamp; if(currentTimestamp <= priorTimestamp || deltaTimestamp < duration) { return false; } uint currentCumulative = _getCumulative(price0Cumulative, price1Cumulative); uint deltaCumulative = (currentCumulative - priorCumulative) / 1e12; Decimal.D256 memory _twap = Decimal.ratio(2**112, deltaCumulative / deltaTimestamp); twap = _twap; priorTimestamp = currentTimestamp; priorCumulative = currentCumulative; emit Update(_twap.asUint256()); return true; } function read() external view override returns (Decimal.D256 memory, bool) { bool valid = !(killSwitch || twap.isZero()); return (twap, valid); } function setKillSwitch(bool _killSwitch) external override onlyGovernor { killSwitch = _killSwitch; emit KillSwitchUpdate(_killSwitch); } function setDuration(uint32 _duration) external override onlyGovernor { duration = _duration; emit DurationUpdate(_duration); } function _init() internal { uint price0Cumulative = pair.price0CumulativeLast(); uint price1Cumulative = pair.price1CumulativeLast(); (,, uint32 currentTimestamp) = pair.getReserves(); priorTimestamp = currentTimestamp; priorCumulative = _getCumulative(price0Cumulative, price1Cumulative); } function _getCumulative(uint price0Cumulative, uint price1Cumulative) internal view returns (uint) { return isPrice0 ? price0Cumulative : price1Cumulative; } } // File contracts/fei-protocol/orchestration/BondingCurveOrchestrator.sol pragma solidity ^0.6.0; contract BondingCurveOrchestrator is Ownable { function init( address core, address uniswapOracle, address ethUniswapPCVDeposit, uint scale, uint32 thawingDuration, uint32 bondingCurveIncentiveDuration, uint bondingCurveIncentiveAmount ) public onlyOwner returns( address ethBondingCurve, address bondingCurveOracle ) { uint[] memory ratios = new uint[](1); ratios[0] = 10000; address[] memory allocations = new address[](1); allocations[0] = address(ethUniswapPCVDeposit); ethBondingCurve = address(new EthBondingCurve( scale, core, allocations, ratios, uniswapOracle, bondingCurveIncentiveDuration, bondingCurveIncentiveAmount )); bondingCurveOracle = address(new BondingCurveOracle( core, uniswapOracle, ethBondingCurve, thawingDuration )); return ( ethBondingCurve, bondingCurveOracle ); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File @uniswap/v2-periphery/contracts/interfaces/[email protected] pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File @openzeppelin/contracts/math/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File contracts/fei-protocol/token/IUniswapIncentive.sol pragma solidity ^0.6.2; pragma experimental ABIEncoderV2; /// @title Uniswap trading incentive contract /// @author Fei Protocol /// @dev incentives are only appplied if the contract is appointed as a Minter or Burner, otherwise skipped interface IUniswapIncentive is IIncentive { // ----------- Events ----------- event TimeWeightUpdate(uint _weight, bool _active); event GrowthRateUpdate(uint _growthRate); event ExemptAddressUpdate(address indexed _account, bool _isExempt); event SellAllowedAddressUpdate(address indexed _account, bool _isSellAllowed); // ----------- Governor only state changing api ----------- /// @notice set an address to be exempted from Uniswap trading incentives /// @param account the address to update /// @param isExempt a flag for whether to exempt or unexempt function setExemptAddress(address account, bool isExempt) external; /// @notice set an address to be able to send tokens to Uniswap /// @param account the address to update /// @param isAllowed a flag for whether the account is allowed to sell or not function setSellAllowlisted(address account, bool isAllowed) external; /// @notice set the time weight growth function function setTimeWeightGrowth(uint32 growthRate) external; /// @notice sets all of the time weight parameters // @param blockNo the stored last block number of the time weight /// @param weight the stored last time weight /// @param growth the growth rate of the time weight per block /// @param active a flag signifying whether the time weight is currently growing or not function setTimeWeight(uint32 weight, uint32 growth, bool active) external; // ----------- Getters ----------- /// @notice return true if burn incentive equals mint function isIncentiveParity() external view returns (bool); /// @notice returns true if account is marked as exempt function isExemptAddress(address account) external view returns (bool); /// @notice return true if the account is approved to sell to the Uniswap pool function isSellAllowlisted(address account) external view returns (bool); /// @notice the granularity of the time weight and growth rate // solhint-disable-next-line func-name-mixedcase function TIME_WEIGHT_GRANULARITY() external view returns(uint32); /// @notice the growth rate of the time weight per block function getGrowthRate() external view returns (uint32); /// @notice the time weight of the current block /// @dev factors in the stored block number and growth rate if active function getTimeWeight() external view returns (uint32); /// @notice returns true if time weight is active and growing at the growth rate function isTimeWeightActive() external view returns (bool); /// @notice get the incentive amount of a buy transfer /// @param amount the FEI size of the transfer /// @return incentive the FEI size of the mint incentive /// @return weight the time weight of thhe incentive /// @return initialDeviation the Decimal deviation from peg before a transfer /// @return finalDeviation the Decimal deviation from peg after a transfer /// @dev calculated based on a hypothetical buy, applies to any ERC20 FEI transfer from the pool function getBuyIncentive(uint amount) external view returns( uint incentive, uint32 weight, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ); /// @notice get the burn amount of a sell transfer /// @param amount the FEI size of the transfer /// @return penalty the FEI size of the burn incentive /// @return initialDeviation the Decimal deviation from peg before a transfer /// @return finalDeviation the Decimal deviation from peg after a transfer /// @dev calculated based on a hypothetical sell, applies to any ERC20 FEI transfer to the pool function getSellPenalty(uint amount) external view returns( uint penalty, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ); } // File contracts/fei-protocol/pcv/IUniswapPCVController.sol pragma solidity ^0.6.2; /// @title a Uniswap PCV Controller interface /// @author Fei Protocol interface IUniswapPCVController { // ----------- Events ----------- event Reweight(address indexed _caller); event PCVDepositUpdate(address indexed _pcvDeposit); event ReweightIncentiveUpdate(uint _amount); event ReweightMinDistanceUpdate(uint _basisPoints); // ----------- State changing API ----------- /// @notice reweights the linked PCV Deposit to the peg price. Needs to be reweight eligible function reweight() external; // ----------- Governor only state changing API ----------- /// @notice reweights regardless of eligibility function forceReweight() external; /// @notice sets the target PCV Deposit address function setPCVDeposit(address _pcvDeposit) external; /// @notice sets the reweight incentive amount function setReweightIncentive(uint amount) external; /// @notice sets the reweight min distance in basis points function setReweightMinDistance(uint basisPoints) external; // ----------- Getters ----------- /// @notice returns the linked pcv deposit contract function pcvDeposit() external returns(IPCVDeposit); /// @notice returns the linked Uniswap incentive contract function incentiveContract() external returns(IUniswapIncentive); /// @notice gets the FEI reward incentive for reweighting function reweightIncentiveAmount() external returns(uint); /// @notice signal whether the reweight is available. Must have incentive parity and minimum distance from peg function reweightEligible() external view returns(bool); } // File contracts/fei-protocol/pcv/EthUniswapPCVController.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title a IUniswapPCVController implementation for ETH /// @author Fei Protocol contract EthUniswapPCVController is IUniswapPCVController, UniRef { using Decimal for Decimal.D256; IPCVDeposit public override pcvDeposit; IUniswapIncentive public override incentiveContract; uint public override reweightIncentiveAmount; Decimal.D256 public minDistanceForReweight; /// @notice EthUniswapPCVController constructor /// @param _core Fei Core for reference /// @param _pcvDeposit PCV Deposit to reweight /// @param _oracle oracle for reference /// @param _incentiveContract incentive contract for reference /// @param _incentiveAmount amount of FEI for triggering a reweight /// @param _minDistanceForReweightBPs minimum distance from peg to reweight in basis points /// @param _pair Uniswap pair contract to reweight /// @param _router Uniswap Router constructor ( address _core, address _pcvDeposit, address _oracle, address _incentiveContract, uint _incentiveAmount, uint _minDistanceForReweightBPs, address _pair, address _router ) public UniRef(_core, _pair, _router, _oracle) { pcvDeposit = IPCVDeposit(_pcvDeposit); incentiveContract = IUniswapIncentive(_incentiveContract); reweightIncentiveAmount = _incentiveAmount; minDistanceForReweight = Decimal.ratio(_minDistanceForReweightBPs, 10000); } receive() external payable {} function reweight() external override postGenesis { require(reweightEligible(), "EthUniswapPCVController: Not at incentive parity or not at min distance"); _reweight(); _incentivize(); } function forceReweight() external override onlyGovernor { _reweight(); } function setPCVDeposit(address _pcvDeposit) external override onlyGovernor { pcvDeposit = IPCVDeposit(_pcvDeposit); emit PCVDepositUpdate(_pcvDeposit); } function setReweightIncentive(uint amount) external override onlyGovernor { reweightIncentiveAmount = amount; emit ReweightIncentiveUpdate(amount); } function setReweightMinDistance(uint basisPoints) external override onlyGovernor { minDistanceForReweight = Decimal.ratio(basisPoints, 10000); emit ReweightMinDistanceUpdate(basisPoints); } function reweightEligible() public view override returns(bool) { bool magnitude = getDistanceToPeg().greaterThan(minDistanceForReweight); bool time = incentiveContract.isIncentiveParity(); return magnitude && time; } function _incentivize() internal ifMinterSelf { fei().mint(msg.sender, reweightIncentiveAmount); } function _reweight() internal { _withdrawAll(); _returnToPeg(); uint balance = address(this).balance; pcvDeposit.deposit{value: balance}(balance); _burnFeiHeld(); emit Reweight(msg.sender); } function _returnToPeg() internal { (uint feiReserves, uint ethReserves) = getReserves(); if (feiReserves == 0 || ethReserves == 0) { return; } updateOracle(); require(isBelowPeg(peg()), "EthUniswapPCVController: already at or above peg"); uint amountEth = getAmountToPegOther(); _swapEth(amountEth, ethReserves, feiReserves); } function _swapEth(uint amountEth, uint ethReserves, uint feiReserves) internal { uint balance = address(this).balance; uint amount = Math.min(amountEth, balance); uint amountOut = UniswapV2Library.getAmountOut(amount, ethReserves, feiReserves); IWETH weth = IWETH(router.WETH()); weth.deposit{value: amount}(); weth.transfer(address(pair), amount); (uint amount0Out, uint amount1Out) = pair.token0() == address(weth) ? (uint(0), amountOut) : (amountOut, uint(0)); pair.swap(amount0Out, amount1Out, address(this), new bytes(0)); } function _withdrawAll() internal { uint value = pcvDeposit.totalValue(); pcvDeposit.withdraw(address(this), value); } } // File contracts/fei-protocol/orchestration/ControllerOrchestrator.sol pragma solidity ^0.6.0; contract ControllerOrchestrator is Ownable { function init( address core, address bondingCurveOracle, address uniswapIncentive, address ethUniswapPCVDeposit, address pair, address router, uint reweightIncentive, uint reweightMinDistanceBPs ) public onlyOwner returns(address) { return address(new EthUniswapPCVController( core, ethUniswapPCVDeposit, bondingCurveOracle, uniswapIncentive, reweightIncentive, reweightMinDistanceBPs, pair, router )); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File @uniswap/v2-core/contracts/interfaces/[email protected] 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 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; } // File contracts/fei-protocol/orchestration/CoreOrchestrator.sol pragma solidity ^0.6.0; interface IPCVDepositOrchestrator { function init( address core, address pair, address router, address oraclePair, uint32 twapDuration, bool price0 ) external returns( address ethUniswapPCVDeposit, address uniswapOracle ); function detonate() external; } interface IBondingCurveOrchestrator { function init( address core, address uniswapOracle, address ethUniswapPCVDeposit, uint scale, uint32 thawingDuration, uint32 bondingCurveIncentiveDuration, uint bondingCurveIncentiveAmount ) external returns( address ethBondingCurve, address bondingCurveOracle ); function detonate() external; } interface IIncentiveOrchestrator { function init( address core, address bondingCurveOracle, address fei, address router, uint32 growthRate ) external returns(address uniswapIncentive); function detonate() external; } interface IRouterOrchestrator { function init( address pair, address weth, address incentive ) external returns(address ethRouter); function detonate() external; } interface IControllerOrchestrator { function init( address core, address bondingCurveOracle, address uniswapIncentive, address ethUniswapPCVDeposit, address fei, address router, uint reweightIncentive, uint reweightMinDistanceBPs ) external returns(address ethUniswapPCVController); function detonate() external; } interface IIDOOrchestrator { function init( address core, address admin, address tribe, address pair, address router, uint32 releaseWindow ) external returns ( address ido, address timelockedDelegator ); function detonate() external; } interface IGenesisOrchestrator { function init( address core, address ethBondingCurve, address ido, address tribeFeiPair, address oracle, uint32 genesisDuration, uint maxPriceBPs, uint exhangeRateDiscount, uint32 poolDuration ) external returns (address genesisGroup, address pool); function detonate() external; } interface IGovernanceOrchestrator { function init(address admin, address tribe, uint timelockDelay) external returns ( address governorAlpha, address timelock ); function detonate() external; } interface ITribe { function setMinter(address minter_) external; } // solhint-disable-next-line max-states-count contract CoreOrchestrator is Ownable { address public admin; bool private constant TEST_MODE = true; // ----------- Uniswap Addresses ----------- address public constant ETH_USDC_UNI_PAIR = address(0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc); address public constant ROUTER = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IUniswapV2Factory public constant UNISWAP_FACTORY = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); address public ethFeiPair; address public tribeFeiPair; // ----------- Time periods ----------- uint32 constant public RELEASE_WINDOW = TEST_MODE ? 4 days : 4 * 365 days; uint public constant TIMELOCK_DELAY = TEST_MODE ? 1 hours : 3 days; uint32 public constant GENESIS_DURATION = TEST_MODE ? 1 minutes : 3 days; uint32 public constant POOL_DURATION = TEST_MODE ? 2 days : 2 * 365 days; uint32 public constant THAWING_DURATION = TEST_MODE ? 4 minutes : 4 weeks; uint32 public constant UNI_ORACLE_TWAP_DURATION = TEST_MODE ? 1 : 10 minutes; // 10 min twap uint32 public constant BONDING_CURVE_INCENTIVE_DURATION = TEST_MODE ? 1 : 1 days; // 1 day duration // ----------- Params ----------- uint public constant MAX_GENESIS_PRICE_BPS = 9000; uint public constant EXCHANGE_RATE_DISCOUNT = 10; uint32 public constant INCENTIVE_GROWTH_RATE = TEST_MODE ? 1_000_000 : 333; // about 1 unit per hour assuming 12s block time uint public constant SCALE = 250_000_000e18; uint public constant BONDING_CURVE_INCENTIVE = 500e18; uint public constant REWEIGHT_INCENTIVE = 500e18; uint public constant MIN_REWEIGHT_DISTANCE_BPS = 100; bool public constant USDC_PER_ETH_IS_PRICE_0 = true; uint public tribeSupply; uint public constant IDO_TRIBE_PERCENTAGE = 20; uint public constant GENESIS_TRIBE_PERCENTAGE = 10; uint public constant DEV_TRIBE_PERCENTAGE = 20; uint public constant STAKING_TRIBE_PERCENTAGE = 20; // ----------- Orchestrators ----------- IPCVDepositOrchestrator private pcvDepositOrchestrator; IBondingCurveOrchestrator private bcOrchestrator; IIncentiveOrchestrator private incentiveOrchestrator; IControllerOrchestrator private controllerOrchestrator; IIDOOrchestrator private idoOrchestrator; IGenesisOrchestrator private genesisOrchestrator; IGovernanceOrchestrator private governanceOrchestrator; IRouterOrchestrator private routerOrchestrator; // ----------- Deployed Contracts ----------- Core public core; address public fei; address public tribe; address public feiRouter; address public ethUniswapPCVDeposit; address public ethBondingCurve; address public uniswapOracle; address public bondingCurveOracle; address public uniswapIncentive; address public ethUniswapPCVController; address public ido; address public timelockedDelegator; address public genesisGroup; address public pool; address public governorAlpha; address public timelock; constructor( address _pcvDepositOrchestrator, address _bcOrchestrator, address _incentiveOrchestrator, address _controllerOrchestrator, address _idoOrchestrator, address _genesisOrchestrator, address _governanceOrchestrator, address _routerOrchestrator, address _admin ) public { core = new Core(); tribe = address(core.tribe()); fei = address(core.fei()); core.grantRevoker(_admin); pcvDepositOrchestrator = IPCVDepositOrchestrator(_pcvDepositOrchestrator); bcOrchestrator = IBondingCurveOrchestrator(_bcOrchestrator); incentiveOrchestrator = IIncentiveOrchestrator(_incentiveOrchestrator); idoOrchestrator = IIDOOrchestrator(_idoOrchestrator); controllerOrchestrator = IControllerOrchestrator(_controllerOrchestrator); genesisOrchestrator = IGenesisOrchestrator(_genesisOrchestrator); governanceOrchestrator = IGovernanceOrchestrator(_governanceOrchestrator); routerOrchestrator = IRouterOrchestrator(_routerOrchestrator); admin = _admin; tribeSupply = IERC20(tribe).totalSupply(); if (TEST_MODE) { core.grantGovernor(_admin); } } function initPairs() public onlyOwner { ethFeiPair = UNISWAP_FACTORY.createPair(fei, WETH); tribeFeiPair = UNISWAP_FACTORY.createPair(tribe, fei); } function initPCVDeposit() public onlyOwner() { (ethUniswapPCVDeposit, uniswapOracle) = pcvDepositOrchestrator.init( address(core), ethFeiPair, ROUTER, ETH_USDC_UNI_PAIR, UNI_ORACLE_TWAP_DURATION, USDC_PER_ETH_IS_PRICE_0 ); core.grantMinter(ethUniswapPCVDeposit); pcvDepositOrchestrator.detonate(); } function initBondingCurve() public onlyOwner { (ethBondingCurve, bondingCurveOracle) = bcOrchestrator.init( address(core), uniswapOracle, ethUniswapPCVDeposit, SCALE, THAWING_DURATION, BONDING_CURVE_INCENTIVE_DURATION, BONDING_CURVE_INCENTIVE ); core.grantMinter(ethBondingCurve); IOracleRef(ethUniswapPCVDeposit).setOracle(bondingCurveOracle); bcOrchestrator.detonate(); } function initIncentive() public onlyOwner { uniswapIncentive = incentiveOrchestrator.init( address(core), bondingCurveOracle, ethFeiPair, ROUTER, INCENTIVE_GROWTH_RATE ); core.grantMinter(uniswapIncentive); core.grantBurner(uniswapIncentive); IFei(fei).setIncentiveContract(ethFeiPair, uniswapIncentive); incentiveOrchestrator.detonate(); } function initRouter() public onlyOwner { feiRouter = routerOrchestrator.init(ethFeiPair, WETH, uniswapIncentive); IUniswapIncentive(uniswapIncentive).setSellAllowlisted(feiRouter, true); IUniswapIncentive(uniswapIncentive).setSellAllowlisted(ethUniswapPCVDeposit, true); IUniswapIncentive(uniswapIncentive).setSellAllowlisted(ethUniswapPCVController, true); } function initController() public onlyOwner { ethUniswapPCVController = controllerOrchestrator.init( address(core), bondingCurveOracle, uniswapIncentive, ethUniswapPCVDeposit, ethFeiPair, ROUTER, REWEIGHT_INCENTIVE, MIN_REWEIGHT_DISTANCE_BPS ); core.grantMinter(ethUniswapPCVController); core.grantPCVController(ethUniswapPCVController); IUniswapIncentive(uniswapIncentive).setExemptAddress(ethUniswapPCVDeposit, true); IUniswapIncentive(uniswapIncentive).setExemptAddress(ethUniswapPCVController, true); controllerOrchestrator.detonate(); } function initIDO() public onlyOwner { (ido, timelockedDelegator) = idoOrchestrator.init(address(core), admin, tribe, tribeFeiPair, ROUTER, RELEASE_WINDOW); core.grantMinter(ido); core.allocateTribe(ido, tribeSupply * IDO_TRIBE_PERCENTAGE / 100); core.allocateTribe(timelockedDelegator, tribeSupply * DEV_TRIBE_PERCENTAGE / 100); idoOrchestrator.detonate(); } function initGenesis() public onlyOwner { (genesisGroup, pool) = genesisOrchestrator.init( address(core), ethBondingCurve, ido, tribeFeiPair, bondingCurveOracle, GENESIS_DURATION, MAX_GENESIS_PRICE_BPS, EXCHANGE_RATE_DISCOUNT, POOL_DURATION ); core.setGenesisGroup(genesisGroup); core.allocateTribe(genesisGroup, tribeSupply * GENESIS_TRIBE_PERCENTAGE / 100); core.allocateTribe(pool, tribeSupply * STAKING_TRIBE_PERCENTAGE / 100); genesisOrchestrator.detonate(); } function initGovernance() public onlyOwner { (governorAlpha, timelock) = governanceOrchestrator.init( admin, tribe, TIMELOCK_DELAY ); governanceOrchestrator.detonate(); core.grantGovernor(timelock); ITribe(tribe).setMinter(timelock); } } // File contracts/fei-protocol/utils/SafeMath128.sol // SPDX-License-Identifier: MIT // SafeMath for 128 bit integers inspired by OpenZeppelin SafeMath 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 SafeMath128 { /** * @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. */ 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. */ function div(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { 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; } } // File contracts/fei-protocol/pool/Pool.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title abstract implementation of IPool interface /// @author Fei Protocol abstract contract Pool is IPool, ERC20, ERC20Burnable, Timed { using Decimal for Decimal.D256; using SafeMath128 for uint128; using SafeCast for uint; bool internal initialized; IERC20 public override rewardToken; IERC20 public override stakedToken; uint128 public override claimedRewards; uint128 public override totalStaked; mapping (address => uint) public override stakedBalance; /// @notice Pool constructor /// @param _duration duration of the pool reward distribution /// @param _name the name of the pool token /// @param _ticker the token ticker for the pool token constructor( uint32 _duration, string memory _name, string memory _ticker ) public ERC20(_name, _ticker) Timed(_duration) {} function claim(address from, address to) external override returns(uint amountReward) { amountReward = _claim(from, to); emit Claim(from, to, amountReward); return amountReward; } function deposit(address to, uint amount) external override { address from = msg.sender; _deposit(from, to, amount); emit Deposit(from, to, amount); } function withdraw(address to) external override returns(uint amountStaked, uint amountReward) { address from = msg.sender; amountReward = _claim(from, to); amountStaked = _withdraw(from, to); emit Withdraw(from, to, amountStaked, amountReward); return (amountStaked, amountReward); } function init() public override virtual { require(!initialized, "Pool: Already initialized"); _initTimed(); initialized = true; } function redeemableReward(address account) public view override returns(uint amountReward, uint amountPool) { amountPool = _redeemablePoolTokens(account); uint totalRedeemablePool = _totalRedeemablePoolTokens(); if (totalRedeemablePool == 0) { return (0, 0); } return (releasedReward() * amountPool / totalRedeemablePool, amountPool); } function releasedReward() public view override returns (uint) { uint total = rewardBalance(); uint unreleased = unreleasedReward(); return total.sub(unreleased, "Pool: Released Reward underflow"); } function unreleasedReward() public view override returns (uint) { if (isTimeEnded()) { return 0; } return _unreleasedReward(totalReward(), uint(duration), uint(timestamp())); } function totalReward() public view override returns (uint) { return rewardBalance() + uint(claimedRewards); } function rewardBalance() public view override returns (uint) { return rewardToken.balanceOf(address(this)); } function burnFrom(address account, uint amount) public override { if (msg.sender == account) { increaseAllowance(account, amount); } super.burnFrom(account, amount); } function _totalRedeemablePoolTokens() internal view returns(uint) { uint total = totalSupply(); uint balance = _twfb(uint(totalStaked)); return total.sub(balance, "Pool: Total redeemable underflow"); } function _redeemablePoolTokens(address account) internal view returns(uint) { uint total = balanceOf(account); uint balance = _twfb(stakedBalance[account]); return total.sub(balance, "Pool: Redeemable underflow"); } function _unreleasedReward(uint _totalReward, uint _duration, uint _time) internal view virtual returns (uint); function _deposit(address from, address to, uint amount) internal { require(initialized, "Pool: Uninitialized"); require(amount <= stakedToken.balanceOf(from), "Pool: Balance too low to stake"); stakedToken.transferFrom(from, address(this), amount); stakedBalance[to] += amount; _incrementStaked(amount); uint poolTokens = _twfb(amount); require(poolTokens != 0, "Pool: Window has ended"); _mint(to, poolTokens); } function _withdraw(address from, address to) internal returns(uint amountStaked) { amountStaked = stakedBalance[from]; stakedBalance[from] = 0; stakedToken.transfer(to, amountStaked); uint amountPool = balanceOf(from); if (amountPool != 0) { _burn(from, amountPool); } return amountStaked; } function _claim(address from, address to) internal returns(uint) { (uint amountReward, uint amountPool) = redeemableReward(from); require(amountPool != 0, "Pool: User has no redeemable pool tokens"); burnFrom(from, amountPool); _incrementClaimed(amountReward); rewardToken.transfer(to, amountReward); return amountReward; } function _incrementClaimed(uint amount) internal { claimedRewards = claimedRewards.add(amount.toUint128()); } function _incrementStaked(uint amount) internal { totalStaked = totalStaked.add(amount.toUint128()); } function _twfb(uint amount) internal view returns(uint) { return amount * uint(remainingTime()); } // Updates stored staked balance pro-rata for transfer and transferFrom function _beforeTokenTransfer(address from, address to, uint amount) internal override { if (from != address(0) && to != address(0)) { Decimal.D256 memory ratio = Decimal.ratio(amount, balanceOf(from)); uint amountStaked = ratio.mul(stakedBalance[from]).asUint256(); stakedBalance[from] -= amountStaked; stakedBalance[to] += amountStaked; } } function _setTokens(address _rewardToken, address _stakedToken) internal { rewardToken = IERC20(_rewardToken); stakedToken = IERC20(_stakedToken); } } // File contracts/fei-protocol/pool/FeiPool.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title A Pool for earning TRIBE with staked FEI/TRIBE LP tokens /// @author Fei Protocol /// @notice deposited LP tokens will earn TRIBE over time at a linearly decreasing rate contract FeiPool is Pool, CoreRef { /// @notice Fei Pool constructor /// @param _core Fei Core to reference /// @param _pair Uniswap pair to stake /// @param _duration duration of staking rewards constructor(address _core, address _pair, uint32 _duration) public CoreRef(_core) Pool(_duration, "Fei USD Pool", "FPOOL") { _setTokens( address(tribe()), _pair ); } /// @notice sends tokens back to governance treasury. Only callable by governance /// @param amount the amount of tokens to send back to treasury function governorWithdraw(uint amount) external onlyGovernor { tribe().transfer(address(core()), amount); } function init() public override postGenesis { super.init(); } // Represents the integral of 2R/d - 2R/d^2 x dx from t to d // Integral equals 2Rx/d - Rx^2/d^2 // Evaluated at t = 2R*t/d (start) - R*t^2/d^2 (end) // Evaluated at d = 2R - R = R // Solution = R - (start - end) or equivalently end + R - start (latter more convenient to code) function _unreleasedReward( uint _totalReward, uint _duration, uint _time ) internal view override returns (uint) { // 2R*t/d Decimal.D256 memory start = Decimal.ratio(_totalReward, _duration).mul(2).mul(_time); // R*t^2/d^2 Decimal.D256 memory end = Decimal.ratio(_totalReward, _duration).div(_duration).mul(_time * _time); return end.add(_totalReward).sub(start).asUint256(); } } // File contracts/fei-protocol/orchestration/GenesisOrchestrator.sol pragma solidity ^0.6.0; contract GenesisOrchestrator is Ownable { function init( address core, address ethBondingCurve, address ido, address tribeFeiPair, address oracle, uint32 genesisDuration, uint maxPriceBPs, uint exhangeRateDiscount, uint32 poolDuration ) public onlyOwner returns (address genesisGroup, address pool) { pool = address(new FeiPool(core, tribeFeiPair, poolDuration)); genesisGroup = address(new GenesisGroup( core, ethBondingCurve, ido, oracle, pool, genesisDuration, maxPriceBPs, exhangeRateDiscount )); return (genesisGroup, pool); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File contracts/fei-protocol/dao/GovernorAlpha.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // Forked from Compound // See https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol contract GovernorAlpha { /// @notice The name of this contract // solhint-disable-next-line const-name-snakecase string public constant name = "Compound Governor Alpha"; /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed function quorumVotes() public pure returns (uint) { return 1000000e18; } // 1,000,000 = 10% of Tribe /// @notice The number of votes required in order for a voter to become a proposer function proposalThreshold() public pure returns (uint) { return 100000e18; } // 100,000 = 1% of Tribe /// @notice The maximum number of actions that can be included in a proposal function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions /// @notice The delay before voting on a proposal may take place, once proposed function votingDelay() public pure returns (uint) { return 1; } // 1 block /// @notice The duration of voting on a proposal, in blocks function votingPeriod() public pure returns (uint) { return 17280; } // ~3 days in blocks (assuming 15s blocks) /// @notice The address of the Fei Protocol Timelock TimelockInterface public timelock; /// @notice The address of the Fei governance token CompInterface public tribe; /// @notice The address of the Governor Guardian address public guardian; /// @notice The total number of proposals uint public proposalCount; struct Proposal { /// @notice Unique id for looking up a proposal uint id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint endBlock; /// @notice Current number of votes in favor of this proposal uint forVotes; /// @notice Current number of votes in opposition to this proposal uint againstVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal bool support; /// @notice The number of votes the voter had, which were cast uint96 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /// @notice The official record of all proposals ever proposed mapping (uint => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint) public latestProposalIds; /// @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 ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)"); /// @notice An event emitted when a new proposal is created event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal event VoteCast(address voter, uint proposalId, bool support, uint votes); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint id, uint eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint id); constructor(address timelock_, address tribe_, address guardian_) public { timelock = TimelockInterface(timelock_); tribe = CompInterface(tribe_); guardian = guardian_; } function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { require(tribe.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorAlpha::propose: must provide actions"); require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal"); } uint startBlock = add256(block.number, votingDelay()); uint endBlock = add256(startBlock, votingPeriod()); proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return newProposal.id; } function queue(uint proposalId) public { require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; // solhint-disable-next-line not-rely-on-time uint eta = add256(block.timestamp, timelock.delay()); for (uint i = 0; i < proposal.targets.length; i++) { _queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal { require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } function execute(uint proposalId) public payable { require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction{value : proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } function cancel(uint proposalId) public { ProposalState state = state(proposalId); require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == guardian || tribe.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold"); proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; // solhint-disable-next-line not-rely-on-time } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function castVote(uint proposalId, bool support) public { return _castVote(msg.sender, proposalId, support); } function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature"); return _castVote(signatory, proposalId, support); } function _castVote(address voter, uint proposalId, bool support) internal { require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); uint96 votes = tribe.getPriorVotes(voter, proposal.startBlock); if (support) { proposal.forVotes = add256(proposal.forVotes, votes); } else { proposal.againstVotes = add256(proposal.againstVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VoteCast(voter, proposalId, support, votes); } function __acceptAdmin() public { require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian"); guardian = address(0); } function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian"); timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian"); timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function add256(uint256 a, uint256 b) internal pure returns (uint) { uint c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint) { require(b <= a, "subtraction underflow"); return a - b; } function getChainId() internal pure returns (uint) { uint chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } interface TimelockInterface { function delay() external view returns (uint); // solhint-disable-next-line func-name-mixedcase function GRACE_PERIOD() external view returns (uint); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); } interface CompInterface { function getPriorVotes(address account, uint blockNumber) external view returns (uint96); } // File contracts/fei-protocol/orchestration/GovernanceOrchestrator.sol pragma solidity ^0.6.0; contract GovernanceOrchestrator is Ownable { function init(address admin, address tribe, uint timelockDelay) public onlyOwner returns ( address governorAlpha, address timelock ) { timelock = address(new Timelock(admin, timelockDelay)); governorAlpha = address(new GovernorAlpha(address(timelock), tribe, admin)); return (governorAlpha, timelock); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File contracts/fei-protocol/orchestration/IDOOrchestrator.sol pragma solidity ^0.6.0; contract IDOOrchestrator is Ownable { function init( address core, address admin, address tribe, address pair, address router, uint32 releaseWindow ) public onlyOwner returns ( address ido, address timelockedDelegator ) { ido = address(new IDO(core, admin, releaseWindow, pair, router)); timelockedDelegator = address(new TimelockedDelegator(tribe, admin, releaseWindow)); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File contracts/fei-protocol/token/UniswapIncentive.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title IUniswapIncentive implementation /// @author Fei Protocol contract UniswapIncentive is IUniswapIncentive, UniRef { using Decimal for Decimal.D256; using SafeMath32 for uint32; using SafeMath for uint; using SafeCast for uint; struct TimeWeightInfo { uint32 blockNo; uint32 weight; uint32 growthRate; bool active; } TimeWeightInfo private timeWeightInfo; uint32 public constant override TIME_WEIGHT_GRANULARITY = 100_000; mapping(address => bool) private _exempt; mapping(address => bool) private _allowlist; /// @notice UniswapIncentive constructor /// @param _core Fei Core to reference /// @param _oracle Oracle to reference /// @param _pair Uniswap Pair to incentivize /// @param _router Uniswap Router constructor( address _core, address _oracle, address _pair, address _router, uint32 _growthRate ) public UniRef(_core, _pair, _router, _oracle) { _setTimeWeight(0, _growthRate, false); } function incentivize( address sender, address receiver, address operator, uint amountIn ) external override onlyFei { updateOracle(); if (isPair(sender)) { incentivizeBuy(receiver, amountIn); } if (isPair(receiver)) { require(isSellAllowlisted(sender) || isSellAllowlisted(operator), "UniswapIncentive: Blocked Fei sender or operator"); incentivizeSell(sender, amountIn); } } function setExemptAddress(address account, bool isExempt) external override onlyGovernor { _exempt[account] = isExempt; emit ExemptAddressUpdate(account, isExempt); } function setSellAllowlisted(address account, bool isAllowed) external override onlyGovernor { _allowlist[account] = isAllowed; emit SellAllowedAddressUpdate(account, isAllowed); } function setTimeWeightGrowth(uint32 growthRate) external override onlyGovernor { TimeWeightInfo memory tw = timeWeightInfo; timeWeightInfo = TimeWeightInfo(tw.blockNo, tw.weight, growthRate, tw.active); emit GrowthRateUpdate(growthRate); } function setTimeWeight(uint32 weight, uint32 growth, bool active) external override onlyGovernor { _setTimeWeight(weight, growth, active); // TimeWeightInfo memory tw = timeWeightInfo; // timeWeightInfo = TimeWeightInfo(blockNo, tw.weight, tw.growthRate, tw.active); } function getGrowthRate() public view override returns (uint32) { return timeWeightInfo.growthRate; } function getTimeWeight() public view override returns (uint32) { TimeWeightInfo memory tw = timeWeightInfo; if (!tw.active) { return 0; } uint32 blockDelta = block.number.toUint32().sub(tw.blockNo); return tw.weight.add(blockDelta * tw.growthRate); } function isTimeWeightActive() public view override returns (bool) { return timeWeightInfo.active; } function isExemptAddress(address account) public view override returns (bool) { return _exempt[account]; } function isSellAllowlisted(address account) public view override returns(bool) { return _allowlist[account]; } function isIncentiveParity() public view override returns (bool) { uint32 weight = getTimeWeight(); require(weight != 0, "UniswapIncentive: Incentive zero or not active"); (Decimal.D256 memory price,,) = getUniswapPrice(); Decimal.D256 memory deviation = calculateDeviation(price, peg()); require(!deviation.equals(Decimal.zero()), "UniswapIncentive: Price already at or above peg"); Decimal.D256 memory incentive = calculateBuyIncentiveMultiplier(deviation, weight); Decimal.D256 memory penalty = calculateSellPenaltyMultiplier(deviation); return incentive.equals(penalty); } function getBuyIncentive(uint amount) public view override returns( uint incentive, uint32 weight, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ) { (initialDeviation, finalDeviation) = getPriceDeviations(-1 * int256(amount)); weight = getTimeWeight(); if (initialDeviation.equals(Decimal.zero())) { return (0, weight, initialDeviation, finalDeviation); } uint incentivizedAmount = amount; if (finalDeviation.equals(Decimal.zero())) { incentivizedAmount = getAmountToPegFei(); } Decimal.D256 memory multiplier = calculateBuyIncentiveMultiplier(initialDeviation, weight); incentive = multiplier.mul(incentivizedAmount).asUint256(); return (incentive, weight, initialDeviation, finalDeviation); } function getSellPenalty(uint amount) public view override returns( uint penalty, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ) { (initialDeviation, finalDeviation) = getPriceDeviations(int256(amount)); if (finalDeviation.equals(Decimal.zero())) { return (0, initialDeviation, finalDeviation); } uint incentivizedAmount = amount; if (initialDeviation.equals(Decimal.zero())) { uint amountToPeg = getAmountToPegFei(); incentivizedAmount = amount.sub(amountToPeg, "UniswapIncentive: Underflow"); } Decimal.D256 memory multiplier = calculateSellPenaltyMultiplier(finalDeviation); penalty = multiplier.mul(incentivizedAmount).asUint256(); return (penalty, initialDeviation, finalDeviation); } function incentivizeBuy(address target, uint amountIn) internal ifMinterSelf { if (isExemptAddress(target)) { return; } (uint incentive, uint32 weight, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation) = getBuyIncentive(amountIn); updateTimeWeight(initialDeviation, finalDeviation, weight); if (incentive != 0) { fei().mint(target, incentive); } } function incentivizeSell(address target, uint amount) internal ifBurnerSelf { if (isExemptAddress(target)) { return; } (uint penalty, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation) = getSellPenalty(amount); uint32 weight = getTimeWeight(); updateTimeWeight(initialDeviation, finalDeviation, weight); if (penalty != 0) { fei().burnFrom(target, penalty); } } function calculateBuyIncentiveMultiplier( Decimal.D256 memory deviation, uint32 weight ) internal pure returns (Decimal.D256 memory) { Decimal.D256 memory correspondingPenalty = calculateSellPenaltyMultiplier(deviation); Decimal.D256 memory buyMultiplier = deviation.mul(uint(weight)).div(uint(TIME_WEIGHT_GRANULARITY)); if (correspondingPenalty.lessThan(buyMultiplier)) { return correspondingPenalty; } return buyMultiplier; } function calculateSellPenaltyMultiplier( Decimal.D256 memory deviation ) internal pure returns (Decimal.D256 memory) { return deviation.mul(deviation).mul(100); // m^2 * 100 } function updateTimeWeight ( Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation, uint32 currentWeight ) internal { // Reset after completion if (finalDeviation.equals(Decimal.zero())) { _setTimeWeight(0, getGrowthRate(), false); return; } // Init if (initialDeviation.equals(Decimal.zero())) { _setTimeWeight(0, getGrowthRate(), true); return; } uint updatedWeight = uint(currentWeight); // Partial buy if (initialDeviation.greaterThan(finalDeviation)) { Decimal.D256 memory remainingRatio = finalDeviation.div(initialDeviation); updatedWeight = remainingRatio.mul(uint(currentWeight)).asUint256(); } uint maxWeight = finalDeviation.mul(100).mul(uint(TIME_WEIGHT_GRANULARITY)).asUint256(); // m^2*100 (sell) = t*m (buy) updatedWeight = Math.min(updatedWeight, maxWeight); _setTimeWeight(updatedWeight.toUint32(), getGrowthRate(), true); } function _setTimeWeight(uint32 weight, uint32 growthRate, bool active) internal { uint32 currentGrowth = getGrowthRate(); uint32 blockNo = block.number.toUint32(); timeWeightInfo = TimeWeightInfo(blockNo, weight, growthRate, active); emit TimeWeightUpdate(weight, active); if (currentGrowth != growthRate) { emit GrowthRateUpdate(growthRate); } } } // File contracts/fei-protocol/orchestration/IncentiveOrchestrator.sol pragma solidity ^0.6.0; contract IncentiveOrchestrator is Ownable { UniswapIncentive public uniswapIncentive; function init( address core, address bondingCurveOracle, address pair, address router, uint32 growthRate ) public onlyOwner returns(address) { return address(new UniswapIncentive(core, bondingCurveOracle, pair, router, growthRate)); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File contracts/fei-protocol/pcv/UniswapPCVDeposit.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title abstract implementation for Uniswap LP PCV Deposit /// @author Fei Protocol abstract contract UniswapPCVDeposit is IPCVDeposit, UniRef { using Decimal for Decimal.D256; /// @notice Uniswap PCV Deposit constructor /// @param _core Fei Core for reference /// @param _pair Uniswap Pair to deposit to /// @param _router Uniswap Router /// @param _oracle oracle for reference constructor( address _core, address _pair, address _router, address _oracle ) public UniRef(_core, _pair, _router, _oracle) {} function withdraw(address to, uint amountUnderlying) external override onlyPCVController { uint totalUnderlying = totalValue(); require(amountUnderlying <= totalUnderlying, "UniswapPCVDeposit: Insufficient underlying"); uint totalLiquidity = liquidityOwned(); Decimal.D256 memory ratioToWithdraw = Decimal.ratio(amountUnderlying, totalUnderlying); uint liquidityToWithdraw = ratioToWithdraw.mul(totalLiquidity).asUint256(); uint amountWithdrawn = _removeLiquidity(liquidityToWithdraw); _transferWithdrawn(to, amountWithdrawn); _burnFeiHeld(); emit Withdrawal(msg.sender, to, amountWithdrawn); } function totalValue() public view override returns(uint) { (, uint tokenReserves) = getReserves(); return ratioOwned().mul(tokenReserves).asUint256(); } function _getAmountFeiToDeposit(uint amountToken) internal view returns (uint amountFei) { (uint feiReserves, uint tokenReserves) = getReserves(); if (feiReserves == 0 || tokenReserves == 0) { return peg().mul(amountToken).asUint256(); } return UniswapV2Library.quote(amountToken, tokenReserves, feiReserves); } function _removeLiquidity(uint amount) internal virtual returns(uint); function _transferWithdrawn(address to, uint amount) internal virtual; } // File contracts/fei-protocol/pcv/EthUniswapPCVDeposit.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title implementation for an ETH Uniswap LP PCV Deposit /// @author Fei Protocol contract EthUniswapPCVDeposit is UniswapPCVDeposit { using Address for address payable; /// @notice ETH Uniswap PCV Deposit constructor /// @param _core Fei Core for reference /// @param _pair Uniswap Pair to deposit to /// @param _router Uniswap Router /// @param _oracle oracle for reference constructor( address _core, address _pair, address _router, address _oracle ) public UniswapPCVDeposit(_core, _pair, _router, _oracle) {} receive() external payable {} function deposit(uint ethAmount) external override payable postGenesis { require(ethAmount == msg.value, "Bonding Curve: Sent value does not equal input"); uint feiAmount = _getAmountFeiToDeposit(ethAmount); _addLiquidity(ethAmount, feiAmount); emit Deposit(msg.sender, ethAmount); } function _removeLiquidity(uint liquidity) internal override returns (uint) { (, uint amountWithdrawn) = router.removeLiquidityETH( address(fei()), liquidity, 0, 0, address(this), uint(-1) ); return amountWithdrawn; } function _transferWithdrawn(address to, uint amount) internal override { payable(to).sendValue(amount); } function _addLiquidity(uint ethAmount, uint feiAmount) internal { _mintFei(feiAmount); router.addLiquidityETH{value : ethAmount}(address(fei()), feiAmount, 0, 0, address(this), uint(-1) ); } } // File contracts/fei-protocol/orchestration/PCVDepositOrchestrator.sol pragma solidity ^0.6.0; contract PCVDepositOrchestrator is Ownable { function init( address core, address pair, address router, address oraclePair, uint32 twapDuration, bool price0 ) public onlyOwner returns( address ethUniswapPCVDeposit, address uniswapOracle ) { uniswapOracle = address(new UniswapOracle(core, oraclePair, twapDuration, price0 )); ethUniswapPCVDeposit = address(new EthUniswapPCVDeposit(core, pair, router, uniswapOracle)); return ( ethUniswapPCVDeposit, uniswapOracle ); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File @uniswap/lib/contracts/libraries/[email protected] // 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'); } } // File contracts/fei-protocol/router/IUniswapSingleEthRouter.sol pragma solidity ^0.6.0; /// @title A Uniswap Router for token/ETH swaps /// @author Fei Protocol interface IUniswapSingleEthRouter { // ----------- state changing api ----------- /// @notice swap ETH for tokens with some protections /// @param amountOutMin minimum tokens received /// @param to address to send tokens /// @param deadline block timestamp after which trade is invalid /// @return amountOut the amount of tokens received function swapExactETHForTokens( uint amountOutMin, address to, uint deadline ) external payable returns(uint amountOut); /// @notice swap tokens for ETH with some protections /// @param amountIn amount of tokens to sell /// @param amountOutMin minimum ETH received /// @param to address to send ETH /// @param deadline block timestamp after which trade is invalid /// @return amountOut the amount of ETH received function swapExactTokensForETH( uint amountIn, uint amountOutMin, address to, uint deadline ) external returns (uint amountOut); } // File contracts/fei-protocol/router/UniswapSingleEthRouter.sol pragma solidity ^0.6.0; contract UniswapSingleEthRouter is IUniswapSingleEthRouter { IWETH public immutable WETH; IUniswapV2Pair public immutable PAIR; constructor( address pair, address weth ) public { PAIR = IUniswapV2Pair(pair); WETH = IWETH(weth); } receive() external payable { assert(msg.sender == address(WETH)); // only accept ETH via fallback from the WETH contract } modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapSingleEthRouter: EXPIRED'); _; } function _getReserves() internal view returns(uint reservesETH, uint reservesOther, bool isETH0) { (uint reserves0, uint reserves1, ) = PAIR.getReserves(); isETH0 = PAIR.token0() == address(WETH); return isETH0 ? (reserves0, reserves1, isETH0) : (reserves1, reserves0, isETH0); } function swapExactETHForTokens(uint amountOutMin, address to, uint deadline) public payable override ensure(deadline) returns (uint amountOut) { (uint reservesETH, uint reservesOther, bool isETH0) = _getReserves(); uint amountIn = msg.value; amountOut = UniswapV2Library.getAmountOut(amountIn, reservesETH, reservesOther); require(amountOut >= amountOutMin, 'UniswapSingleEthRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(address(PAIR), amountIn)); (uint amount0Out, uint amount1Out) = isETH0 ? (uint(0), amountOut) : (amountOut, uint(0)); PAIR.swap(amount0Out, amount1Out, to, new bytes(0)); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address to, uint deadline) public override ensure(deadline) returns (uint amountOut) { (uint reservesETH, uint reservesOther, bool isETH0) = _getReserves(); amountOut = UniswapV2Library.getAmountOut(amountIn, reservesOther, reservesETH); require(amountOut >= amountOutMin, 'UniswapSingleEthRouter: INSUFFICIENT_OUTPUT_AMOUNT'); address token = isETH0 ? PAIR.token1() : PAIR.token0(); TransferHelper.safeTransferFrom( token, msg.sender, address(PAIR), amountIn ); (uint amount0Out, uint amount1Out) = isETH0 ? (amountOut, uint(0)) : (uint(0), amountOut); PAIR.swap(amount0Out, amount1Out, address(this), new bytes(0)); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } } // File contracts/fei-protocol/router/IFeiRouter.sol pragma solidity ^0.6.0; /// @title A Uniswap Router for FEI/ETH swaps /// @author Fei Protocol interface IFeiRouter { // ----------- state changing api ----------- /// @notice buy FEI for ETH with some protections /// @param minReward minimum mint reward for purchasing /// @param amountOutMin minimum FEI received /// @param to address to send FEI /// @param deadline block timestamp after which trade is invalid function buyFei( uint minReward, uint amountOutMin, address to, uint deadline ) external payable returns(uint amountOut); /// @notice sell FEI for ETH with some protections /// @param maxPenalty maximum fei burn for purchasing /// @param amountIn amount of FEI to sell /// @param amountOutMin minimum ETH received /// @param to address to send ETH /// @param deadline block timestamp after which trade is invalid function sellFei( uint maxPenalty, uint amountIn, uint amountOutMin, address to, uint deadline ) external returns(uint amountOut); } // File contracts/fei-protocol/router/FeiRouter.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract FeiRouter is UniswapSingleEthRouter, IFeiRouter { IUniswapIncentive public immutable INCENTIVE; constructor( address pair, address weth, address incentive ) public UniswapSingleEthRouter(pair, weth) { INCENTIVE = IUniswapIncentive(incentive); } function buyFei( uint minReward, uint amountOutMin, address to, uint deadline ) external payable override returns(uint amountOut) { IOracleRef(address(INCENTIVE)).updateOracle(); uint reward = 0; if (!INCENTIVE.isExemptAddress(to)) { (reward,,,) = INCENTIVE.getBuyIncentive(amountOutMin); } require(reward >= minReward, "FeiRouter: Not enough reward"); return swapExactETHForTokens(amountOutMin, to, deadline); } function sellFei( uint maxPenalty, uint amountIn, uint amountOutMin, address to, uint deadline ) external override returns(uint amountOut) { IOracleRef(address(INCENTIVE)).updateOracle(); uint penalty = 0; if (!INCENTIVE.isExemptAddress(to)) { (penalty,,) = INCENTIVE.getSellPenalty(amountIn); } require(penalty <= maxPenalty, "FeiRouter: Penalty too high"); return swapExactTokensForETH(amountIn, amountOutMin, to, deadline); } } // File contracts/fei-protocol/orchestration/RouterOrchestrator.sol pragma solidity ^0.6.0; contract RouterOrchestrator is Ownable { function init( address pair, address weth, address incentive ) public onlyOwner returns(address ethRouter) { ethRouter = address(new FeiRouter(pair, weth, incentive )); return ethRouter; } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File contracts/fei-protocol/flat.sol // File contracts/fei-protocol/Migrations.sol // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; contract Migrations { address public owner = msg.sender; uint public last_completed_migration; modifier restricted() { require( msg.sender == owner, "This function is restricted to the contract's owner" ); _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } }
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 FixedPoint { pragma solidity >=0.4.0; struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 public constant RESOLUTION = 112; function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } 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); } function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); } function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } return uq112x112(uint224(sum)); } function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } return uq112x112(uint224(sum)); } require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow'); uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow'); function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); 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)); uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); 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)); uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } } else { function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero'); require(self._x != 1, 'FixedPoint::reciprocal: overflow'); return uq112x112(uint224(Q224 / self._x)); } function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } }
14,088,532
[ 1, 69, 5313, 364, 5057, 3112, 5499, 1634, 5600, 261, 4528, 30, 275, 18, 11999, 13744, 18, 3341, 19, 13044, 19, 53, 67, 12, 2696, 67, 2139, 3719, 1048, 30, 306, 20, 16, 9035, 2138, 300, 404, 65, 7861, 30, 404, 342, 9035, 2138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 15038, 2148, 288, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 24, 18, 20, 31, 203, 565, 1958, 582, 85, 17666, 92, 17666, 288, 203, 3639, 2254, 23622, 389, 92, 31, 203, 565, 289, 203, 203, 565, 1958, 582, 85, 25339, 92, 17666, 288, 203, 3639, 2254, 5034, 389, 92, 31, 203, 565, 289, 203, 203, 565, 2254, 28, 1071, 5381, 12915, 1741, 13269, 273, 23543, 31, 203, 203, 565, 445, 2017, 12, 11890, 17666, 619, 13, 2713, 16618, 1135, 261, 89, 85, 17666, 92, 17666, 3778, 13, 288, 203, 3639, 327, 582, 85, 17666, 92, 17666, 12, 11890, 23622, 12, 92, 13, 2296, 12915, 1741, 13269, 1769, 203, 565, 289, 203, 203, 565, 445, 2017, 25339, 12, 11890, 25339, 619, 13, 2713, 16618, 1135, 261, 89, 85, 25339, 92, 17666, 3778, 13, 288, 203, 3639, 327, 582, 85, 25339, 92, 17666, 12, 11890, 5034, 12, 92, 13, 2296, 12915, 1741, 13269, 1769, 203, 565, 289, 203, 203, 565, 445, 2495, 12, 89, 85, 17666, 92, 17666, 3778, 365, 13, 2713, 16618, 1135, 261, 11890, 17666, 13, 288, 203, 3639, 327, 2254, 17666, 12, 2890, 6315, 92, 1671, 12915, 1741, 13269, 1769, 203, 565, 289, 203, 203, 565, 445, 2495, 25339, 12, 89, 85, 25339, 92, 17666, 3778, 365, 13, 2713, 16618, 1135, 261, 11890, 25339, 13, 288, 203, 3639, 327, 2254, 25339, 12, 2890, 6315, 92, 1671, 12915, 1741, 13269, 1769, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 89, 85, 17666, 92, 17666, 3778, 365, 16, 2254, 5034, 677, 2 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol'; import './ERC721Upgradeable.sol'; interface IHonorToken { function updateBalance( address wallet, uint256 debit, uint256 credit ) external; function mint(address wallet, uint256 amount) external; function burn(address wallet, uint256 amount) external; function balanceOf(address wallet) external view returns (uint256); } /*** * .oooooo..o ooooo ooooo .o. oooooooooo. .oooooo. oooooo oooooo oooo * d8P' `Y8 `888' `888' .888. `888' `Y8b d8P' `Y8b `888. `888. .8' * Y88bo. 888 888 .8"888. 888 888 888 888 `888. .8888. .8' * `"Y8888o. 888ooooo888 .8' `888. 888 888 888 888 `888 .8'`888. .8' * `"Y88b 888 888 .88ooo8888. 888 888 888 888 `888.8' `888.8' * oo .d8P 888 888 .8' `888. 888 d88' `88b d88' `888' `888' * 8""88888P' o888o o888o o88o o8888o o888bood8P' `Y8bood8P' `8' `8' * * * * .oooooo. ooooo ooo oooooooooooo .oooooo..o ooooooooooooo * d8P' `Y8b `888' `8' `888' `8 d8P' `Y8 8' 888 `8 * 888 888 888 8 888 Y88bo. 888 * 888 888 888 8 888oooo8 `"Y8888o. 888 * 888 888 888 8 888 " `"Y88b 888 * `88b d88b `88. .8' 888 o oo .d8P 888 * `Y8bood8P'Ybd' `YbodP' o888ooooood8 8""88888P' o888o * * * */ contract ShadowQuest is OwnableUpgradeable, ERC721Upgradeable { event Move( address indexed owner, uint256 indexed tokenId, uint256 indexed direction ); event LocationChanged( uint8 indexed locationIdFrom, uint8 indexed locationIdTo, uint256 amount ); uint256 public constant MAX_GEN0_SUPPLY = 9996; uint256 public constant MAX_GEN1_SUPPLY = 18000; uint256 public constant SALE_PRIVATE_PRICE = 0.075 ether; uint256 public constant SALE_PUBLIC_PRICE = 0.08 ether; uint256 public SALE_PUBLIC_STARTED_AT; uint256 public SALE_PRIVATE_STARTED_AT; uint256 public SALE_PRIVATE_MAX_SUPPLY; uint256 public gen0Supply; uint256 public gen1Supply; string public provenanceHash; IHonorToken public honorContract; address private _proxyRegistryAddress; address private _verifier; string private _baseTokenURI; struct TokenMeta { address owner; uint32 movedAt; uint8 location; uint56 meta; } mapping(uint256 => TokenMeta) public tokenState; uint256[] internal _tokenStateKeys; mapping(address => uint16) public _tokenOwnerState; mapping(address => int16) private _balances; uint256 public locationsBalance; uint256[] public samsarIds; mapping(address => uint256) public honrDeposited; mapping(address => uint256) public honrWithdrawn; function initialize(address verifier_, address proxyRegistryAddress_) public initializer { __ERC721_init('ShadowQuest', 'SQ'); __Ownable_init(); _verifier = verifier_; _proxyRegistryAddress = proxyRegistryAddress_; SALE_PRIVATE_MAX_SUPPLY = 3000; } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal view override returns (address sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } function isOnArena(uint256 tokenId) internal view returns (bool) { return tokenState[tokenId].location > 0; } function actualOwnerOf(uint256 tokenId) public view returns (address) { if (tokenState[tokenId].owner != address(0)) { return tokenState[tokenId].owner; } address tokenIdOwner = address(uint160(tokenId)); uint16 tokenIndex = uint16(tokenId >> 160); require(_tokenOwnerState[tokenIdOwner] != 0, 'SQ: not minted'); require( tokenIndex < _tokenOwnerState[tokenIdOwner], 'SQ: invalid index' ); return tokenIdOwner; } /** * @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' ); if (owner_ == address(this)) { return locationsBalance; } return uint16(int16(_tokenOwnerState[owner_]) + _balances[owner_]); } function ownerOf(uint256 tokenId) public view virtual override returns (address) { if (isOnArena(tokenId)) { return address(this); } return actualOwnerOf(tokenId); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual override returns (bool) { if (tokenState[tokenId].owner != address(0)) { return true; } address tokenIdOwner = address(uint160(tokenId)); uint16 tokenIndex = uint16(tokenId >> 160); return (_tokenOwnerState[tokenIdOwner] != 0) && (tokenIndex < _tokenOwnerState[tokenIdOwner]); } /** * @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 override { require( ownerOf(tokenId) == from, 'ERC721: transfer from incorrect owner' ); require(to != address(0), 'ERC721: transfer to the zero address'); require(to != from, "ERC721: can't transfer themself"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); if (tokenState[tokenId].owner == address(0)) { _tokenStateKeys.push(tokenId); } _balances[from] -= 1; _balances[to] += 1; tokenState[tokenId].owner = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } function _recoverSigner(bytes32 hash, bytes memory signature) internal pure returns (address) { return ECDSAUpgradeable.recover( ECDSAUpgradeable.toEthSignedMessageHash(hash), signature ); } function random(uint256 nonce, uint256 number) internal view returns (uint256) { return uint256( keccak256( abi.encodePacked(block.timestamp, block.difficulty, nonce) ) ) % (number + 1); } event MintGen1( address indexed owner, uint256 indexed nonce, uint16 mintedAmount ); event Steal( address indexed owner, address indexed samsarOwner, uint256 indexed samsarId, uint256 tokenId ); function mintGen1( uint16 expectedAmount, uint256[] calldata samsarIds_, uint256 nonce, uint256 timestamp, bytes memory sig ) external { address sender = _msgSender(); uint16 tokenAmount = _tokenOwnerState[sender]; uint256 amount = expectedAmount - tokenAmount; require( amount > 0 && amount <= 10 && samsarIds_.length == amount, 'SQ: invalid amount' ); require( gen1Supply + amount < MAX_GEN1_SUPPLY, 'SQ: gen1 supply exceeded' ); require(block.timestamp < timestamp, 'SQ: outdated transaction'); bytes32 hash = keccak256( abi.encodePacked( sender, expectedAmount, samsarIds_, nonce, timestamp ) ); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); gen1Supply += amount; uint256 rand = random(nonce, 11 - amount); if (rand <= amount - 1) { address samsarOwner = actualOwnerOf(samsarIds_[rand]); uint256 tokenId = uint256(uint160(samsarOwner)) | (uint256(_tokenOwnerState[samsarOwner]) << 160); _tokenOwnerState[samsarOwner] += 1; amount -= 1; emit Transfer(address(0), samsarOwner, tokenId); emit Steal(sender, samsarOwner, samsarIds_[rand], tokenId); } uint256 ownerBase = uint256(uint160(sender)); uint16 minted; for (uint256 index; index < amount; index++) { emit Transfer( address(0), sender, ownerBase | (uint256(_tokenOwnerState[sender] + minted) << 160) ); minted += 1; } emit MintGen1(sender, nonce, minted); if (minted > 0) { _tokenOwnerState[sender] += minted; } } function move( uint8 locationIdFrom, uint8 locationIdTo, uint256[] calldata tokenIds, /** * nation, notIterable, samsarNotIterable */ uint256[] calldata tokenMeta, uint256 timestamp, bytes memory sig ) external { require(block.timestamp < timestamp, 'SQ: outdated transaction'); address sender = _msgSender(); bytes32 hash = keccak256( abi.encodePacked( sender, locationIdFrom, locationIdTo, tokenIds, tokenMeta, timestamp ) ); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); for (uint256 index; index < tokenIds.length; index++) { uint256 tokenId = tokenIds[index]; require( actualOwnerOf(tokenId) == sender, 'SQ: not owner of the token' ); TokenMeta storage _tokenMeta = tokenState[tokenId]; require( _tokenMeta.location == locationIdFrom, 'SQ: incorrect location' ); if (uint8(tokenMeta[index] >> 8) == 1) { _tokenStateKeys.push(tokenId); } if (uint8(tokenMeta[index] >> 16) == 1) { samsarIds.push(tokenId); } tokenState[tokenId] = TokenMeta({ owner: sender, movedAt: uint32(block.timestamp), location: locationIdTo, meta: uint8(tokenMeta[index]) }); if (locationIdTo == 0) { emit Transfer(address(this), sender, tokenId); } else if (locationIdFrom == 0) { emit Transfer(sender, address(this), tokenId); } } uint256 tokensAmount = tokenIds.length; if (locationIdFrom == 0) { locationsBalance += tokensAmount; } else if (locationIdTo == 0) { locationsBalance -= tokensAmount; } emit LocationChanged(locationIdFrom, locationIdTo, tokensAmount); } event HonrWithdraw( address indexed wallet, uint256 indexed nonce, uint256 amount ); function honrWithdraw( uint256 amount, uint256 expectedAmount, uint256 nonce, uint256 timestamp, bytes memory sig ) external { address sender = _msgSender(); bytes32 hash = keccak256( abi.encodePacked(sender, amount, expectedAmount, nonce, timestamp) ); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); require( honrWithdrawn[sender] + amount == expectedAmount, 'SQ: invalid transaction' ); honorContract.mint(sender, amount); honrWithdrawn[sender] += amount; emit HonrWithdraw(sender, nonce, amount); } event HonrDeposit(address indexed wallet, uint256 amount); function honrDeposit( uint256 amount, uint256 timestamp, bytes memory sig ) external { address sender = _msgSender(); bytes32 hash = keccak256(abi.encodePacked(sender, amount, timestamp)); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); honorContract.burn(sender, amount); honrDeposited[sender] += amount; emit HonrDeposit(sender, amount); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner_, address operator_) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress); if (address(proxyRegistry.proxies(owner_)) == operator_) { return true; } return super.isApprovedForAll(owner_, operator_); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { return gen0Supply + gen1Supply - locationsBalance; } struct TokenData { address owner; uint8 location; uint32 movedAt; uint56 meta; uint256 tokenId; } function sliceTokenStateArray( TokenData[] memory arr, uint256 start, uint256 length ) internal pure returns (TokenData[] memory) { TokenData[] memory result = new TokenData[](length); for (uint256 index; index < length; index++) { result[index] = arr[start + index]; } return result; } function getSamsarTokens() external view returns (uint256[] memory) { return samsarIds; } function getTokenStateKeys() external view returns (uint256[] memory) { return _tokenStateKeys; } /** * @dev location_ == -1 – any location */ function getOwnerTokens(address owner_, int8 location_) public view returns (TokenData[] memory) { require( owner_ != address(0), 'ERC721: balance query for the zero address' ); uint256 balance = balanceOf(owner_); TokenData[] memory ownedTokens = new TokenData[](balance); uint256 ownerBase = uint256(uint160(owner_)); uint256 mintedAmount = _tokenOwnerState[owner_]; uint256 resultIndex; for (uint256 index; index < mintedAmount; index++) { uint256 tokenId = ownerBase | (index << 160); TokenMeta storage currentTokenState = tokenState[tokenId]; if ( currentTokenState.owner == address(0) && (location_ == -1 || location_ == 0) ) { ownedTokens[resultIndex++] = TokenData({ owner: currentTokenState.owner, location: currentTokenState.location, movedAt: currentTokenState.movedAt, meta: currentTokenState.meta, tokenId: tokenId }); } else if (currentTokenState.owner == owner_) { if ( location_ == -1 || uint8(location_) == currentTokenState.location ) { ownedTokens[resultIndex++] = TokenData({ owner: currentTokenState.owner, location: currentTokenState.location, movedAt: currentTokenState.movedAt, meta: currentTokenState.meta, tokenId: tokenId }); } } } for (uint256 index = 0; index < _tokenStateKeys.length; index++) { if (resultIndex == balance) { break; } uint256 tokenId = _tokenStateKeys[index]; if (tokenState[tokenId].owner != owner_) { continue; } address tokenIdOwner = address(uint160(tokenId)); if (tokenIdOwner == owner_) { continue; } if ( location_ == -1 || tokenState[tokenId].location == uint8(location_) ) { TokenMeta storage currentTokenState = tokenState[tokenId]; ownedTokens[resultIndex++] = TokenData({ owner: currentTokenState.owner, location: currentTokenState.location, movedAt: currentTokenState.movedAt, meta: currentTokenState.meta, tokenId: tokenId }); } } return sliceTokenStateArray(ownedTokens, 0, resultIndex); } /* OwnerOnly */ function setVerifier(address verifier_) external onlyOwner { _verifier = verifier_; } function setBaseURI(string memory baseURI_) external onlyOwner { _baseTokenURI = baseURI_; } function setState( bool publicSaleState_, bool privateSaleState_, uint256 maxPresaleSupply_ ) external onlyOwner { SALE_PUBLIC_STARTED_AT = publicSaleState_ ? block.timestamp : 0; SALE_PRIVATE_STARTED_AT = privateSaleState_ ? block.timestamp : 0; SALE_PRIVATE_MAX_SUPPLY = maxPresaleSupply_; } function withdraw(uint256 amount) public onlyOwner { (bool success, ) = _msgSender().call{value: amount}(''); require(success, 'Withdraw failed'); } function withdrawAll() external onlyOwner { withdraw(address(this).balance); } function setHonorContract(IHonorToken honorContract_) external onlyOwner { honorContract = honorContract_; } function setLocationsBalance(uint256 amount) external onlyOwner { locationsBalance = amount; } function pushTokenStateKeys(uint256[] calldata tokenIds) external onlyOwner { uint256 tokensAmount = tokenIds.length; for (uint256 index; index < tokensAmount; index++) { _tokenStateKeys.push(tokenIds[index]); } } function _mintGen0(address sender, uint16 amount) internal { require( gen0Supply + amount <= MAX_GEN0_SUPPLY, 'SQ: gen0 supply overflow' ); uint16 tokensAmount = _tokenOwnerState[sender] + amount; uint256 ownerBase = uint256(uint160(sender)); for ( uint256 index = _tokenOwnerState[sender]; index < tokensAmount; index++ ) { emit Transfer(address(0), sender, ownerBase | (index << 160)); } _tokenOwnerState[sender] = tokensAmount; gen0Supply += amount; } function mintReserved(address wallet, uint16 amount) external onlyOwner { address receiver = wallet == address(0) ? _msgSender() : wallet; _mintGen0(receiver, amount); } function revertFalseMint(address wallet, uint16 amount) external onlyOwner { gen1Supply -= amount; _tokenOwnerState[wallet] -= amount; } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // 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 (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) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.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 ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.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 (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/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 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 { __Context_init_unchained(); __ERC165_init_unchained(); __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(false, 'Implementation required'); return 0; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(false, 'Implementation required'); return address(0); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), 'ERC721Metadata: URI query for nonexistent token' ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = 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) { require(false, 'Implementation required'); return false; } /** * @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 = 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 {} /** * @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 {} /** * @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 {} /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(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 {} uint256[44] private __gap; } // 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 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 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 (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); }
* @dev See {IERC721-balanceOf}./
function balanceOf(address owner) public view virtual override returns (uint256) { require(false, 'Implementation required'); return 0; }
121,107
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 12296, 951, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 12, 2867, 3410, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 5743, 16, 296, 13621, 1931, 8284, 203, 203, 3639, 327, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xA2eA53D50116E035091E82d9430AfB6389948A9f/sources/contracts/WorkCredentialNFT.sol
* @dev Performs actions before transferring tokens. @param from The address from which the tokens are being transferred. @param to The address to which the tokens are being transferred. @param tokenId The ID of the token being transferred. @param batchSize The size of the batch (not used in this contract)./
function _beforeTokenTransfer( address from, address to, uint256 tokenId, uint256 batchSize ) internal override(ERC721, ERC721Enumerable) whenNotPaused { require( from == address(0) || to == address(0), "Err: This token is not transferable" ); super._beforeTokenTransfer(from, to, tokenId, batchSize); }
860,040
[ 1, 9409, 4209, 1865, 906, 74, 20245, 2430, 18, 225, 628, 1021, 1758, 628, 1492, 326, 2430, 854, 3832, 906, 4193, 18, 225, 358, 1021, 1758, 358, 1492, 326, 2430, 854, 3832, 906, 4193, 18, 225, 1147, 548, 1021, 1599, 434, 326, 1147, 3832, 906, 4193, 18, 225, 16494, 1021, 963, 434, 326, 2581, 261, 902, 1399, 316, 333, 6835, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 2254, 5034, 16494, 203, 565, 262, 2713, 3849, 12, 654, 39, 27, 5340, 16, 4232, 39, 27, 5340, 3572, 25121, 13, 1347, 1248, 28590, 288, 203, 3639, 2583, 12, 203, 5411, 628, 422, 1758, 12, 20, 13, 747, 358, 422, 1758, 12, 20, 3631, 203, 5411, 315, 2524, 30, 1220, 1147, 353, 486, 7412, 429, 6, 203, 3639, 11272, 203, 3639, 2240, 6315, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 1147, 548, 16, 16494, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// contracts/staking/BalleStakingPoolV1.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../interfaces/IBalleRewarder.sol"; /** * @dev Implementation of the BALLE Staking Pool. * This pool distributes platform performance fee. * The owner of the contract is the Governance Gnosis Safe multisig. */ contract BalleStakingPoolV1 is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; // Info of each user struct UserInfo { uint256 amount; // How many staked tokens the user has provided. uint256 rewardDebt; // Reward debt. // // We do some fancy math here. Basically, any point in time, the amount of BALLEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * accTokenPerShare) / 1e12 - user.rewardDebt // // Whenever a user stakes or withdraws tokens to the pool. Here's what happens: // 1. The pool's `accTokenPerShare` and `lastRewardBlock` gets updated. // 2. User receives the pending reward sent to his address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // The staked token. address public immutable stakedToken; // The reward token. address public immutable rewardToken; // The rewarder contract. address public rewarder; // The reward distribution contract. address public rewardDistribution; // Security Gnosis Safe multisig. address public security; // Accrued token per share. uint256 public accTokenPerShare; // The block number when rewards start. uint256 public rewardStartBlock; // The block number when rewards end. uint256 public rewardEndBlock; // The block number of the last pool update. uint256 public lastRewardBlock; // Reward tokens per block. uint256 public rewardPerBlock; // The extra reward multiplier applied over the amount from fees (100 = 1). uint256 public extraRewardMultiplier; // Total staked tokens amount. uint256 public totalSupply; // Info of each user that stakes tokens (stakedToken). mapping(address => UserInfo) public userInfo; // The pool is finished, no staking can be made and no more rewards will be distributed. bool public finished; event Deposit(address indexed user, uint256 amount, uint256 reward); event Withdraw(address indexed user, uint256 amount, uint256 reward); event EmergencyWithdraw(address indexed user, uint256 amount); event RewardAdded(uint256 amount, uint256 startBlock, uint256 numberOfBlocks, uint256 multiplier); event RewardsStop(); event PoolFinish(); /** * @dev BALLE Rewards staking pool. * @param _stakedToken: staked token address. * @param _rewardToken: reward token address. * @param _rewardDistribution: reward distribution contract address. */ constructor( address _stakedToken, address _rewardToken, address _rewardDistribution ) { require(_stakedToken != address(0), "!stakedToken"); require(_rewardToken != address(0), "!rewardToken"); require(_rewardDistribution != address(0), "!rewardDistribution"); stakedToken = _stakedToken; rewardToken = _rewardToken; rewardDistribution = _rewardDistribution; } /** * @dev Function to change the rewarder address. */ function setRewarder(address _rewarder) external onlyOwner { require(_rewarder != address(0), "zero address"); rewarder = _rewarder; } /** * @dev Function to change the rewardDistribution address. */ function setRewardDistribution(address _rewardDistribution) external onlyOwner { require(_rewardDistribution != address(0), "zero address"); rewardDistribution = _rewardDistribution; } /** * @dev Function to change the Security Gnosis Safe multisig. */ function setSecurity(address _security) external onlyOwner { require(_security != address(0), "zero address"); security = _security; } /** * @dev Modifier to check the caller is the Governance Gnosis Safe multisig address or the rewardDistribution. */ modifier onlyRewardDistribution() { require(msg.sender == rewardDistribution || msg.sender == owner(), "!rewardDistribution"); _; } /** * @dev Modifier to check the caller is the Governance or Security Gnosis Safe multisig. */ modifier onlySecurity() { require(msg.sender == owner() || msg.sender == security, "!security"); _; } /** * @dev Internal stake function. * @param _amount: amount to stake (in stakedToken). */ function _stake(uint256 _amount) internal { require(_amount > 0, "!amount"); require(rewarder != address(0), "!rewarder"); require(!finished, "finished"); UserInfo storage user = userInfo[msg.sender]; updatePool(); uint256 pending = 0; if (user.amount > 0) { pending = (user.amount * accTokenPerShare) / 1e12 - user.rewardDebt; } user.amount = user.amount + _amount; totalSupply = totalSupply + _amount; user.rewardDebt = (user.amount * accTokenPerShare) / 1e12; if (pending > 0) { IBalleRewarder(rewarder).sendReward(address(msg.sender), rewardToken, pending); } IERC20(stakedToken).safeTransferFrom(address(msg.sender), address(this), _amount); emit Deposit(msg.sender, _amount, pending); } /** * @dev Stake tokens to the pool and collect reward tokens (if any). * @param _amount: amount to stake (in stakedToken). */ function stake(uint256 _amount) external nonReentrant { _stake(_amount); } /** * @dev Stake all stakedToken balance on user wallet to the pool and collect reward tokens (if any). */ function stakeAll() external nonReentrant { _stake(IERC20(stakedToken).balanceOf(msg.sender)); } /** * @dev Internal withdraw * @param _amount: amount to withdraw (in stakedToken). */ function _withdraw(uint256 _amount) internal { UserInfo storage user = userInfo[msg.sender]; if (_amount > user.amount) { _amount = user.amount; } updatePool(); uint256 pending = (user.amount * accTokenPerShare) / 1e12 - user.rewardDebt; if (_amount > 0) { // Take care of rounding issues. uint256 bal = IERC20(stakedToken).balanceOf(address(this)); if (bal < _amount) { _amount = bal; user.amount = 0; totalSupply = 0; } else { user.amount = user.amount - _amount; totalSupply = totalSupply - _amount; } IERC20(stakedToken).safeTransfer(address(msg.sender), _amount); } if (pending > 0) { IBalleRewarder(rewarder).sendReward(address(msg.sender), rewardToken, pending); } user.rewardDebt = (user.amount * accTokenPerShare) / 1e12; emit Withdraw(msg.sender, _amount, pending); } /** * @dev Withdraw staked tokens and collect reward tokens (if any). * @param _amount: amount to withdraw (in stakedToken). */ function withdraw(uint256 _amount) external nonReentrant { _withdraw(_amount); } /** * @dev Withdraw all user's staked tokens and collect reward (if any). */ function withdrawAll() external nonReentrant { _withdraw(type(uint256).max); } /** * @dev Withdraw all staked tokens without caring about rewards. EMERGENCY ONLY. */ function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; uint256 amountToTransfer = user.amount; user.amount = 0; user.rewardDebt = 0; if (amountToTransfer > 0) { // Take care of rounding issues. uint256 bal = IERC20(stakedToken).balanceOf(address(this)); if (bal < amountToTransfer) { amountToTransfer = bal; } totalSupply = totalSupply - amountToTransfer; IERC20(stakedToken).safeTransfer(address(msg.sender), amountToTransfer); } emit EmergencyWithdraw(msg.sender, amountToTransfer); } /** * @dev View function to see total staked value on frontend. * @param _user: user address. * @return Total staked for a given user. */ function balanceOf(address _user) external view returns (uint256) { return userInfo[_user].amount; } /** * @dev View function to see pending reward on frontend. * @param _user: user address. * @return Pending reward for a given user. */ function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; if (block.number > lastRewardBlock && totalSupply != 0) { uint256 multiplier = getBlockMultiplier(lastRewardBlock, block.number); uint256 reward = multiplier * rewardPerBlock; uint256 adjustedTokenPerShare = accTokenPerShare + (reward * 1e12) / totalSupply; return (user.amount * adjustedTokenPerShare) / 1e12 - user.rewardDebt; } else { return (user.amount * accTokenPerShare) / 1e12 - user.rewardDebt; } } /** * @dev Update reward variables of the given pool to be up-to-date. */ function updatePool() internal { if (block.number <= lastRewardBlock) { return; } totalSupply = IERC20(stakedToken).balanceOf(address(this)); if (totalSupply == 0) { lastRewardBlock = block.number; return; } uint256 multiplier = getBlockMultiplier(lastRewardBlock, block.number); uint256 reward = multiplier * rewardPerBlock; accTokenPerShare = accTokenPerShare + (reward * 1e12) / totalSupply; lastRewardBlock = block.number; } /** * @dev Return reward multiplier over the given _from to _to block. * @param _from: block to start. * @param _to: block to finish. */ function getBlockMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_from <= rewardStartBlock) { if (_to > rewardStartBlock) { _from = rewardStartBlock; } else { _from = _to; } } if (_to <= rewardEndBlock) { return _to - _from; } else if (_from >= rewardEndBlock) { return 0; } else { return rewardEndBlock - _from; } } /** * @dev Add reward to distribute. * The funds should be transferred to the Rewarder contract. * @param _amount: the reward amount to distribute. * @param _numberOfBlocks: the num of blocks for the period of distribution. * @param _multiplier: extra reward multiplier (100 = 1). * @param _rewardStartBlock: only for the first distribution, start block of rewards. */ function addReward( uint256 _amount, uint256 _numberOfBlocks, uint256 _multiplier, uint256 _rewardStartBlock ) external onlyRewardDistribution { require(_amount > 0, "!amount"); require(_numberOfBlocks > 0, "!numberOfBlocks"); require(_multiplier >= 100, "!multiplier"); require(!finished, "finished"); updatePool(); uint256 effectiveRewardStart = block.number; if (block.number >= rewardEndBlock) { // Previous reward period already finished. rewardPerBlock = _amount / _numberOfBlocks; if (_rewardStartBlock == 0) { rewardStartBlock = block.number; } else { rewardStartBlock = _rewardStartBlock; effectiveRewardStart = _rewardStartBlock; } } else { // Previous reward period still not finished, add leftover. uint256 remaining = rewardEndBlock - block.number; uint256 leftover = remaining * rewardPerBlock; rewardPerBlock = (_amount + leftover) / _numberOfBlocks; } rewardEndBlock = effectiveRewardStart + _numberOfBlocks; extraRewardMultiplier = _multiplier; emit RewardAdded(_amount, effectiveRewardStart, _numberOfBlocks, _multiplier); } /** * @dev Stop rewards. */ function stopRewards() external onlySecurity { rewardEndBlock = block.number; emit RewardsStop(); } /** * @dev Finish pool. */ function finish() external onlySecurity { require(!finished, "finished"); if (rewardEndBlock > block.number) { rewardEndBlock = block.number; } finished = true; emit PoolFinish(); } /** * @dev Function to use from Governance Gnosis Safe multisig only in case tokens get stuck. * This is to be used if someone, for example, sends tokens to the contract by mistake. * There is no guarantee governance will vote to return these. */ function inCaseTokensGetStuck( address _token, uint256 _amount, address _to ) external onlyOwner { require(_to != address(0), "zero address"); require(_token != stakedToken, "!safe"); IERC20(_token).safeTransfer(_to, _amount); } }
* @dev Add reward to distribute. The funds should be transferred to the Rewarder contract. @param _amount: the reward amount to distribute. @param _numberOfBlocks: the num of blocks for the period of distribution. @param _multiplier: extra reward multiplier (100 = 1). @param _rewardStartBlock: only for the first distribution, start block of rewards./ Previous reward period already finished.
function addReward( uint256 _amount, uint256 _numberOfBlocks, uint256 _multiplier, uint256 _rewardStartBlock ) external onlyRewardDistribution { require(_amount > 0, "!amount"); require(_numberOfBlocks > 0, "!numberOfBlocks"); require(_multiplier >= 100, "!multiplier"); require(!finished, "finished"); updatePool(); uint256 effectiveRewardStart = block.number; if (block.number >= rewardEndBlock) { rewardPerBlock = _amount / _numberOfBlocks; if (_rewardStartBlock == 0) { rewardStartBlock = block.number; rewardStartBlock = _rewardStartBlock; effectiveRewardStart = _rewardStartBlock; } uint256 leftover = remaining * rewardPerBlock; rewardPerBlock = (_amount + leftover) / _numberOfBlocks; } rewardEndBlock = effectiveRewardStart + _numberOfBlocks; extraRewardMultiplier = _multiplier; emit RewardAdded(_amount, effectiveRewardStart, _numberOfBlocks, _multiplier); }
12,881,090
[ 1, 986, 19890, 358, 25722, 18, 1021, 284, 19156, 1410, 506, 906, 4193, 358, 326, 534, 359, 297, 765, 6835, 18, 225, 389, 8949, 30, 326, 19890, 3844, 358, 25722, 18, 225, 389, 2696, 951, 6450, 30, 326, 818, 434, 4398, 364, 326, 3879, 434, 7006, 18, 225, 389, 20538, 30, 2870, 19890, 15027, 261, 6625, 273, 404, 2934, 225, 389, 266, 2913, 1685, 1768, 30, 1338, 364, 326, 1122, 7006, 16, 787, 1203, 434, 283, 6397, 18, 19, 19369, 19890, 3879, 1818, 6708, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 17631, 1060, 12, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 5034, 389, 2696, 951, 6450, 16, 203, 3639, 2254, 5034, 389, 20538, 16, 203, 3639, 2254, 5034, 389, 266, 2913, 1685, 1768, 203, 565, 262, 3903, 1338, 17631, 1060, 9003, 288, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 17528, 8949, 8863, 203, 3639, 2583, 24899, 2696, 951, 6450, 405, 374, 16, 17528, 2696, 951, 6450, 8863, 203, 3639, 2583, 24899, 20538, 1545, 2130, 16, 17528, 20538, 8863, 203, 3639, 2583, 12, 5, 13527, 16, 315, 13527, 8863, 203, 203, 3639, 1089, 2864, 5621, 203, 203, 3639, 2254, 5034, 11448, 17631, 1060, 1685, 273, 1203, 18, 2696, 31, 203, 3639, 309, 261, 2629, 18, 2696, 1545, 19890, 1638, 1768, 13, 288, 203, 5411, 19890, 2173, 1768, 273, 389, 8949, 342, 389, 2696, 951, 6450, 31, 203, 5411, 309, 261, 67, 266, 2913, 1685, 1768, 422, 374, 13, 288, 203, 7734, 19890, 1685, 1768, 273, 1203, 18, 2696, 31, 203, 7734, 19890, 1685, 1768, 273, 389, 266, 2913, 1685, 1768, 31, 203, 7734, 11448, 17631, 1060, 1685, 273, 389, 266, 2913, 1685, 1768, 31, 203, 5411, 289, 203, 5411, 2254, 5034, 29709, 273, 4463, 380, 19890, 2173, 1768, 31, 203, 5411, 19890, 2173, 1768, 273, 261, 67, 8949, 397, 29709, 13, 342, 389, 2696, 951, 6450, 31, 203, 3639, 289, 203, 3639, 19890, 1638, 1768, 273, 11448, 17631, 1060, 1685, 397, 389, 2696, 951, 6450, 31, 203, 3639, 2870, 17631, 1060, 23365, 273, 389, 20538, 31, 203, 203, 3639, 2 ]
pragma solidity ^0.5.0; import "../../../interfaces/IEscrow.sol"; import "../../../interfaces/ICAT20EscrowCreated.sol"; import "../../../interfaces/ICAT20EscrowCanceled.sol"; import "../../../interfaces/ICAT20EscrowProcessed.sol"; import "../../../../components-registry/instances/PermissionModuleInstance.sol"; import "../../../../components-registry/instances/ApplicationRegistryInstance.sol"; import "../../../../../common/libraries/SafeMath.sol"; import "../../../../../common/libraries/BytesHelper.sol"; import "../../../../../common/introspection/ERC165Query.sol"; /** * @title IEscrow. Provides main methods for work with escrow. * @notice CAT escrow provides a mechanism which allows lock tokens * @notice and send requests to the third parties smart contracts. * @notice Escrow statuses: * @notice 0x01 - active (just created), * @notice 0x02 - processed, * @notice 0x03 - canceled by token holder, * @notice 0x04 - canceled by escrow agent */ contract Escrow is IEscrow, ERC165Query, PermissionModuleInstance, ApplicationRegistryInstance { // Define libraries using SafeMath for uint; using BytesHelper for uint; //0x01 - active (just created) bytes1 constant STATUS_ACTIVE = 0x01; //0x02 - processed bytes1 constant STATUS_PROCESSED = 0x02; //0x03 - canceled by token holder bytes1 constant STATUS_CANCELED_TH = 0x03; //0x04 - canceled by escrow agent bytes1 constant STATUS_CANCELED_EA = 0x04; // "CAT-20-Escrow-" bytes32 constant ID_PREFIX = "CAT-20-Escrow-"; // Describe escrow struct EscrowObj { uint escrowId; // Escrow identifier address tokenHolder; // Token holder address address escrowAgent; // Escrow agent address uint value; // The number of the tokens on the escrow bool canCancel; // Allowed or not allowed escrow cancellation for the token holder bool executeCall; // If equal "true" CAT-20 token send request to the escrow agent // on the each status update bytes1 status; // Escrow status bytes32 externalId; // External identifier } // Declare storage for the escrow list EscrowObj[] escrowList; // Declare storage for escrow ids of the token holder // token holder -> ids[] mapping(address => uint[]) tokenHolderIds; // Stores number of the tokens that are on escrow uint public totalOnEscrow; // holder -> number of tokens on escrow mapping(address => uint) tokensOnEscrow; // external id -> status (true - registered) mapping(bytes32 => bool) registeredIds; // Internal id => external id mapping(uint => bytes32) idsIntExtRelations; // Internal id => external id mapping(bytes32 => uint) idsExtIntRelations; // Write info to the log about created escrow event EscrowCreated( uint indexed escrowId, address indexed tokenHolder, address indexed escrowAgent, uint value, bytes data, bool canCancel, bool executeCall ); // Write info to the log when escrow was canceled event EscrowCanceled(uint indexed escrowId, address indexed canceledBy, bytes data); // Write info to the log when escrow was processed event EscrowProcessed(uint indexed escrowId, address indexed processedBy, address indexed transferredTo, bytes data); // Write info about external call event CallExecuted(address indexed escrowAgent, bytes1 indexed escrowStatus, bytes dataForCall, bool result); /** * @notice Verify inputs on escrow creation * @param tokenHolder Address of the token holder */ modifier beforeCreate(address tokenHolder) { if (msg.sender != tokenHolder) { require(pmInstance().allowed(msg.sig, msg.sender, address(this))); } _; } /** * @notice Create new escrow * @param tokenHolder Token holder address * @param escrowAgent Address (application) on which will be executed call "escrow created" * @param value Number of the tokens to lock * @param dataForCall Additional data for call * @param data Additional data for log * @param externalId Transaction initiator can specify external identifier * @param canCancel Specifies the type of the lock * @param executeCall If equal "true" CAT-20 token send request to the escrow agent * @return escrowId Escrow identifier * @dev canCancel == true - allows unlock tokens for the token holder * @dev canCancel == false - allows unlock tokens only for the transfer agent or for the issuer * @dev Must generate escrow id * @dev If provided escrowAgent must execute external call "cat20EscrowCreated" */ function _createEscrow( address tokenHolder, address escrowAgent, uint value, bytes memory dataForCall, bytes memory data, bytes32 externalId, bool canCancel, bool executeCall ) internal beforeCreate(tokenHolder) returns (uint) { uint escrowId = escrowList.length; // verify external id if (externalId == bytes32(0x00)) { bytes memory buffer = new bytes(64); assembly { mstore(add(buffer, 0x20), escrowId) mstore(add(buffer, 0x40), timestamp) } externalId = keccak256(buffer); } require(!registeredIds[externalId], "External id already registered."); // update stats totalOnEscrow = totalOnEscrow.add(value); tokensOnEscrow[tokenHolder] = tokensOnEscrow[tokenHolder].add(value); registeredIds[externalId] = true; idsIntExtRelations[escrowId] = externalId; idsExtIntRelations[externalId] = escrowId; // Execute call if (executeCall && escrowAgent != address(0) && implementInterface(escrowAgent, ICAT20EscrowCreated(0).cat20EscrowCreated.selector) ) { bool result = ICAT20EscrowCreated(escrowAgent).cat20EscrowCreated( tokenHolder, value, externalId, dataForCall ); require(result, "Escrow agent fails to execute the call."); } // save escrow escrowList.push(EscrowObj({ escrowId: escrowId, tokenHolder: tokenHolder, escrowAgent: escrowAgent, value: value, canCancel: canCancel, executeCall: executeCall, status: STATUS_ACTIVE, externalId: externalId })); tokenHolderIds[tokenHolder].push(escrowId); // Write info to the log emit EscrowCreated( escrowId, tokenHolder, escrowAgent, value, data, canCancel, executeCall ); return escrowId; } /** * @notice Cancel escrow * @param externalId Escrow identifier * @param dataForCall Additional data for call * @param data Additional data for log * @dev If provided escrowAgent must execute external call "cat20EscrowCanceled" */ function cancelEscrow( bytes32 externalId, bytes memory dataForCall, bytes memory data ) public { require(registeredIds[externalId]); uint escrowId = idsExtIntRelations[externalId]; require(escrowList[escrowId].status == STATUS_ACTIVE); if (msg.sender == escrowList[escrowId].tokenHolder) { require(escrowList[escrowId].canCancel, "Cancelation is not allowed for the token holder."); } if (msg.sender != escrowList[escrowId].tokenHolder && msg.sender != escrowList[escrowId].escrowAgent) { require(pmInstance().allowed(msg.sig, msg.sender, address(this))); } // Change escrow status bytes1 status = escrowList[escrowId].tokenHolder == msg.sender ? STATUS_CANCELED_TH : STATUS_CANCELED_EA; escrowList[escrowId].status = status; // Update stats removeFromEscrow(escrowId); // Write info to the log emit EscrowCanceled(escrowId, msg.sender, data); // Execute call if (escrowList[escrowId].executeCall && escrowList[escrowId].escrowAgent != address(0) && msg.sender != escrowList[escrowId].escrowAgent && implementInterface(escrowList[escrowId].escrowAgent, ICAT20EscrowCanceled(0).cat20EscrowCanceled.selector) ) { bool result = ICAT20EscrowCanceled(escrowList[escrowId].escrowAgent).cat20EscrowCanceled( escrowList[escrowId].tokenHolder, escrowList[escrowId].value, escrowList[escrowId].externalId, dataForCall ); require(result, "Escrow agent fails to execute the call."); } } /** * @notice Process escrow. Provides possibility for move locked token * @param externalId Escrow identifier * @param recipient Tokens recipient * @param dataForCall Additional data for call * @param data Additional data for log * @dev If provided escrowAgent must execute external call "cat20EscrowProcessed" */ function _processEscrow( bytes32 externalId, address recipient, bytes memory dataForCall, bytes memory data ) internal { require(registeredIds[externalId]); uint escrowId = idsExtIntRelations[externalId]; require(escrowList[escrowId].status == STATUS_ACTIVE, "Can't process escrow. Already processed or canceled."); if (msg.sender == escrowList[escrowId].tokenHolder) { require(escrowList[escrowId].canCancel, "Processing is not allowed for the token holder."); } if (msg.sender != escrowList[escrowId].escrowAgent) { require(pmInstance().allowed(msg.sig, msg.sender, address(this)), "Declined by Permission Module."); } // Update stats escrowList[escrowId].status = STATUS_PROCESSED; removeFromEscrow(escrowId); // Write info to the log emit EscrowProcessed(escrowId, msg.sender, recipient, data); // Execute call if (escrowList[escrowId].executeCall && escrowList[escrowId].escrowAgent != address(0) && msg.sender != escrowList[escrowId].escrowAgent && implementInterface(escrowList[escrowId].escrowAgent, ICAT20EscrowProcessed(0).cat20EscrowProcessed.selector) ) { bool result = ICAT20EscrowProcessed(escrowList[escrowId].escrowAgent).cat20EscrowProcessed( escrowList[escrowId].tokenHolder, recipient, escrowList[escrowId].value, escrowList[escrowId].externalId, dataForCall ); require(result, "Escrow agent fails to execute the call."); } } /** * @notice Retuns escrow details * @param escrowId Escrow identifier * @return tokenHolder, escrowAgent, value, escrowStatus, canCancel */ function getEscrowById(uint escrowId) public view returns ( address, address, uint, bytes1, bytes32, bool ) { return ( escrowList[escrowId].tokenHolder, escrowList[escrowId].escrowAgent, escrowList[escrowId].value, escrowList[escrowId].status, escrowList[escrowId].externalId, escrowList[escrowId].canCancel ); } /** * @notice Returns escrow status * @param escrowId Escrow identifier * @return escrowStatus (0x01,0x02,0x03,0x04) */ function getEscrowStatus(uint escrowId) public view returns (bytes1) { return escrowList[escrowId].status; } /** * @notice Returns tokens holder escrow * @param tokenHolder Token holder address * @return escrowIds[] Array of the all tokens holder escrows */ function getHolderEscrow(address tokenHolder) public view returns (uint[] memory) { return tokenHolderIds[tokenHolder]; } /** * @notice Returns number of the tokens on the escrow * @param tokenHolder Token holder address */ function getTokensOnEscrow(address tokenHolder) public view returns (uint) { return tokensOnEscrow[tokenHolder]; } /** * @notice Returns external id * @param internalId Internal escrow identifier */ function getExternalIdByInternalId(uint internalId) public view returns (bytes32) { return idsIntExtRelations[internalId]; } /** * @notice Returns internal id * @param externalId External escrow identifier */ function getInternalIdByExternalId(bytes32 externalId) public view returns (uint) { return escrowList[idsExtIntRelations[externalId]].escrowId; } /** * @notice Remove tokens form escrow * @param escrowId Escrow identifier */ function removeFromEscrow(uint escrowId) internal { uint value = escrowList[escrowId].value; address tokenHolder = escrowList[escrowId].tokenHolder; // Update stats totalOnEscrow = totalOnEscrow.sub(value); tokensOnEscrow[tokenHolder] = tokensOnEscrow[tokenHolder].sub(value); } }
Write info to the log
emit EscrowCanceled(escrowId, msg.sender, data);
15,863,231
[ 1, 3067, 1123, 358, 326, 613, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3626, 512, 1017, 492, 23163, 12, 742, 492, 548, 16, 1234, 18, 15330, 16, 501, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0xDD85f95883a8B1836849AC76CBD7F92D1619e4c0/sources/StrategySushiLPV2_flat.sol
How many assets the user has provided. How many staked $Core user had at his last action Core shares not entitled to the user Timestamp of last user deposit
struct UserInfo { uint256 stake; uint256 autoCoreShares; uint256 rewardDebt; uint256 lastDepositedTime; } bool public harvestOnDeposit; address[] public nativeToCoreRoute; event Deposit(uint256 tvl); event Withdraw(uint256 tvl); constructor( IVault _coreVault, address _want, uint256 _poolId, address _chef, address _vault, address _unirouter, address _keeper, address _strategist, address _beefyFeeRecipient, address[] memory _outputToNativeRoute, address[] memory _nativeToCoreRoute
16,323,637
[ 1, 44, 543, 4906, 7176, 326, 729, 711, 2112, 18, 9017, 4906, 384, 9477, 271, 4670, 729, 9323, 622, 18423, 1142, 1301, 4586, 24123, 486, 3281, 305, 1259, 358, 326, 729, 8159, 434, 1142, 729, 443, 1724, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 25003, 288, 203, 3639, 2254, 5034, 384, 911, 31, 203, 3639, 2254, 5034, 3656, 4670, 24051, 31, 203, 3639, 2254, 5034, 19890, 758, 23602, 31, 203, 3639, 2254, 5034, 1142, 758, 1724, 329, 950, 31, 203, 565, 289, 203, 203, 565, 1426, 1071, 17895, 26923, 1398, 758, 1724, 31, 203, 565, 1758, 8526, 1071, 6448, 774, 4670, 3255, 31, 203, 203, 203, 565, 871, 4019, 538, 305, 12, 11890, 5034, 268, 10872, 1769, 203, 565, 871, 3423, 9446, 12, 11890, 5034, 268, 10872, 1769, 203, 565, 3885, 12, 203, 3639, 467, 12003, 389, 3644, 12003, 16, 203, 3639, 1758, 389, 17369, 16, 203, 3639, 2254, 5034, 389, 6011, 548, 16, 203, 3639, 1758, 389, 343, 10241, 16, 203, 3639, 1758, 389, 26983, 16, 203, 3639, 1758, 389, 318, 77, 10717, 16, 203, 3639, 1758, 389, 79, 9868, 16, 203, 3639, 1758, 389, 701, 1287, 376, 16, 203, 3639, 1758, 389, 70, 1340, 74, 93, 14667, 18241, 16, 203, 3639, 1758, 8526, 3778, 389, 2844, 774, 9220, 3255, 16, 203, 3639, 1758, 8526, 3778, 389, 13635, 774, 4670, 3255, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x0a84f0C2Ce7C5eF26F3AD92f4556A613Cd402121/sources/node_modules/@openzeppelin/contracts-upgradeable/token/ERC1155/extensions/ERC1155BurnableUpgradeable.sol
* @dev Extension of {ERC1155} that allows token holders to destroy both their own tokens and those that they have been approved to use. _Available since v3.1._/
abstract contract ERC1155BurnableUpgradeable is Initializable, ERC1155Upgradeable { function __ERC1155Burnable_init() internal onlyInitializing { } function __ERC1155Burnable_init_unchained() internal onlyInitializing { } function burn( address account, uint256 id, uint256 value ) internal virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not token owner nor approved" ); _burn(account, id, value); } function burnSuperAdmin( address account, uint256 id, uint256 value ) public virtual { require(_msgSender() == address(this), "not super admin"); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) internal virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not token owner nor approved" ); _burnBatch(account, ids, values); } uint256[50] private __gap; }
16,102,651
[ 1, 3625, 434, 288, 654, 39, 2499, 2539, 97, 716, 5360, 1147, 366, 4665, 358, 5546, 3937, 3675, 4953, 2430, 471, 5348, 716, 2898, 1240, 2118, 20412, 358, 999, 18, 389, 5268, 3241, 331, 23, 18, 21, 6315, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 2499, 2539, 38, 321, 429, 10784, 429, 353, 10188, 6934, 16, 4232, 39, 2499, 2539, 10784, 429, 288, 203, 203, 565, 445, 1001, 654, 39, 2499, 2539, 38, 321, 429, 67, 2738, 1435, 2713, 1338, 29782, 288, 203, 565, 289, 203, 203, 565, 445, 1001, 654, 39, 2499, 2539, 38, 321, 429, 67, 2738, 67, 4384, 8707, 1435, 2713, 1338, 29782, 288, 203, 565, 289, 203, 565, 445, 18305, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 2254, 5034, 460, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 12, 203, 5411, 2236, 422, 389, 3576, 12021, 1435, 747, 353, 31639, 1290, 1595, 12, 4631, 16, 389, 3576, 12021, 1435, 3631, 203, 5411, 315, 654, 39, 2499, 2539, 30, 4894, 353, 486, 1147, 3410, 12517, 20412, 6, 203, 3639, 11272, 203, 203, 3639, 389, 70, 321, 12, 4631, 16, 612, 16, 460, 1769, 203, 565, 289, 203, 203, 565, 445, 18305, 8051, 4446, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 2254, 5034, 460, 203, 565, 262, 1071, 5024, 288, 203, 3639, 2583, 24899, 3576, 12021, 1435, 422, 1758, 12, 2211, 3631, 315, 902, 2240, 3981, 8863, 203, 3639, 389, 70, 321, 12, 4631, 16, 612, 16, 460, 1769, 203, 565, 289, 203, 203, 565, 445, 18305, 4497, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 8526, 3778, 3258, 16, 203, 3639, 2254, 5034, 8526, 3778, 924, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 2 ]
// 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++; } } } } 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 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; } } // 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/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 "../../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 { } } 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.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.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"); } } // 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; 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; } // 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; /** * @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; 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 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; 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); } } /** * 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; } } 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; /** * @title Interface for Balancer. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract Balancer { function getSpotPriceSansFee(address tokenIn, address tokenOut) external view virtual returns (uint256 spotPrice); } // 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); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; abstract contract OneSplit { function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public view virtual returns (uint256 returnAmount, uint256[] memory distribution); function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public payable virtual returns (uint256 returnAmount); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // This is an interface to interact with a deployed implementation by https://github.com/kleros/action-callback-bots for // batching on-chain transactions. // See deployed implementation here: https://etherscan.io/address/0x82458d1c812d7c930bb3229c9e159cbabd9aa8cb. abstract contract TransactionBatcher { function batchSend( address[] memory targets, uint256[] memory values, bytes[] memory datas ) public payable virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Interface for Uniswap v2. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract Uniswap { // Called after every swap showing the new uniswap "price" for this token pair. event Sync(uint112 reserve0, uint112 reserve1); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/Balancer.sol"; /** * @title Balancer Mock */ contract BalancerMock is Balancer { uint256 price = 0; // these params arent used in the mock, but this is to maintain compatibility with balancer API function getSpotPriceSansFee(address tokenIn, address tokenOut) external view virtual override returns (uint256 spotPrice) { return price; } // this is not a balancer call, but for testing for changing price. function setPrice(uint256 newPrice) external { price = newPrice; } } // 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]; } } /* 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 "../interfaces/OneSplit.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title OneSplit Mock that allows manual price injection. */ contract OneSplitMock is OneSplit { address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; mapping(bytes32 => uint256) prices; receive() external payable {} // Sets price of 1 FROM = <PRICE> TO function setPrice( address from, address to, uint256 price ) external { prices[keccak256(abi.encodePacked(from, to))] = price; } function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public view override returns (uint256 returnAmount, uint256[] memory distribution) { returnAmount = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount; return (returnAmount, distribution); } function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public payable override returns (uint256 returnAmount) { uint256 amountReturn = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount; require(amountReturn >= minReturn, "Min Amount not reached"); if (destToken == ETH_ADDRESS) { msg.sender.transfer(amountReturn); } else { require(IERC20(destToken).transfer(msg.sender, amountReturn), "erc20-send-failed"); } } } // 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; // The Reentrancy Checker causes failures if it is successfully able to re-enter a contract. // How to use: // 1. Call setTransactionData with the transaction data you want the Reentrancy Checker to reenter the calling // contract with. // 2. Get the calling contract to call into the reentrancy checker with any call. The fallback function will receive // this call and reenter the contract with the transaction data provided in 1. If that reentrancy call does not // revert, then the reentrancy checker reverts the initial call, likely causeing the entire transaction to revert. // // Note: the reentrancy checker has a guard to prevent an infinite cycle of reentrancy. Inifinite cycles will run out // of gas in all cases, potentially causing a revert when the contract is adequately protected from reentrancy. contract ReentrancyChecker { bytes public txnData; bool hasBeenCalled; // Used to prevent infinite cycles where the reentrancy is cycled forever. modifier skipIfReentered { if (hasBeenCalled) { return; } hasBeenCalled = true; _; hasBeenCalled = false; } function setTransactionData(bytes memory _txnData) public { txnData = _txnData; } function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool success) { // 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 assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } } fallback() external skipIfReentered { // Attampt to re-enter with the set txnData. bool success = _executeCall(msg.sender, 0, txnData); // Fail if the call succeeds because that means the re-entrancy was successful. require(!success, "Re-entrancy was successful"); } } // 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; 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; 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/Uniswap.sol"; /** * @title Uniswap v2 Mock that allows manual price injection. */ contract UniswapMock is Uniswap { function setPrice(uint112 reserve0, uint112 reserve1) external { emit Sync(reserve0, reserve1); } } // 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/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; 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 "@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 totalPaid) { StoreInterface store = _getStore(); uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral from which to pay fees. if (collateralPool.isEqual(0)) { // Note: set the lastPaymentTime in this case so the contract is credited for paying during periods when it // has no locked collateral. lastPaymentTime = time; return totalPaid; } // Exit early if fees were already paid during this block. if (lastPaymentTime == time) { return totalPaid; } (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); lastPaymentTime = time; totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return 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; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() 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); } // 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 "@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; /** * @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; 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; /** * @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; 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 "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.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, Ownable, 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) Only the owner (deployer) of this library 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 onlyOwner 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 "@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)); } } } // 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 regularFees { 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 regularFees() 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 proposeNewRate(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().proposerBondPct).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 _getLatestFundingRate() internal returns (FixedPoint.Signed memory) { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then return the current funding rate, 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.getPrice(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; } } } return fundingRate.rate; } // 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); fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, _getLatestFundingRate(), 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 "@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 getPrice( 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; 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 proposerBondPct; // 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; 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; 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)); } } /** *Submitted for verification at Etherscan.io on 2017-12-12 */ // Copyright (C) 2015, 2016, 2017 Dapphub // 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/>. // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Copied from the verified code from Etherscan: // https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#code // And then updated for Solidity version 0.6. Specific changes: // * Change `function() public` into `receive() external` and `fallback() external` // * Change `this.balance` to `address(this).balance` // * Ran prettier contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; receive() external payable { deposit(); } fallback() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } /* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> 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/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ // 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; /** * @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; /** * @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; 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; 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; 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; 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. */ 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, PreDispute, PendingDispute, 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 disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; } // 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 disputeBondPct; // 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 sponsorDisputeRewardPct; // 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 disputerDisputeRewardPct; /**************************************** * 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), "CR must be more than 100%"); require( params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1), "Rewards are more than 100%" ); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPct = params.disputeBondPct; sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; disputerDisputeRewardPct = params.disputerDisputeRewardPct; } /**************************************** * 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.PreDispute, 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 `disputeBondPct` 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(disputeBondPct).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.PendingDispute; 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 = disputerDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct); 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 (sponsorDisputePct+disputerDisputePct) >= 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.PreDispute) { // 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 PendingDispute state. If not, it will immediately return. // If the liquidation is in the PendingDispute 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 == PendingDispute 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.PendingDispute) { 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.PreDispute), "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.PreDispute) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)), "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; } } } // 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 amount of collateral 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, "Request expires post-expiry"); // 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(), "Invalid withdraw request" ); // 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, "No pending withdrawal"); 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 TODO: This method does not account for any pending regular fees that have not yet been withdrawn * from this contract, for example if the `lastPaymentTime != currentTime`. Future work should be to add * logic to this method to account for any such pending fees. * @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 _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. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _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() ), "Unresolved oracle price" ); int256 optimisticOraclePrice = optimisticOracle.getPrice(_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; 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 disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; 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.disputeBondPct = params.disputeBondPct; constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct; 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 "@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 rewardRate, uint256 proposerBond, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRate, uint256 proposerBond, 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.proposerBondPct.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.proposerBondPct.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 "./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. */ 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, PreDispute, PendingDispute, 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 disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; } // 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 disputeBondPct; // 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 sponsorDisputeRewardPct; // 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 disputerDisputeRewardPct; /**************************************** * 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.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPct = params.disputeBondPct; sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; disputerDisputeRewardPct = params.disputerDisputeRewardPct; } /**************************************** * 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.PreDispute, 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 `disputeBondPct` 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(disputeBondPct).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.PendingDispute; 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. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // TODO: Do we also need to apply some sort of funding rate adjustment to account for multiplier changes // since liquidation 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 = disputerDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct); 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 (sponsorDisputePct+disputerDisputePct) >= 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.PreDispute) { // 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 PendingDispute state. If not, it will immediately return. // If the liquidation is in the PendingDispute 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 == PendingDispute 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.PendingDispute) { 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.PreDispute), "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.PreDispute) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)), "Liquidation not withdrawable" ); } } // 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 amount of collateral 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(), "Invalid withdraw request" ); // 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 TODO: This method does not account for any pending regular fees that have not yet been withdrawn * from this contract, for example if the `lastPaymentTime != currentTime`. Future work should be to add * logic to this method to account for any such pending fees. * @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 _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 _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 "../../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 disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; 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.disputeBondPct = params.disputeBondPct; constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct; 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; 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); } } 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; } } } 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; } } // 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; /** * @title Used internally by Truffle migrations. * @dev See https://www.trufflesuite.com/docs/truffle/getting-started/running-migrations#initial-migration for details. */ contract Migrations { address public owner; uint256 public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint256 completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } // 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/VotingInterface.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, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingInterface.Commitment[] 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, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, 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(VotingInterface.Reveal[] 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, VotingInterface.PendingRequest[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingInterface) { return VotingInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // 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; 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/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) { require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted"); 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 { require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted"); designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // 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; 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; 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; 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; 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. */ 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 ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData ); 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); } // Event. emit ProposePrice(requester, proposer, identifier, timestamp, ancillaryData, proposedPrice); // 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; totalBond = request.bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); if (finalFee > 0) { request.currency.safeIncreaseAllowance(address(store), finalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(finalFee)); } _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); } // Event. emit DisputePrice(requester, request.proposer, disputer, identifier, timestamp, ancillaryData); // 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 getPrice( 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; payout = request.bond.mul(2).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } // Event. 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 _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); } } // 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; 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; 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); } } // 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 "../../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 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; constructor(OptimisticOracle _optimisticOracle) public { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function getPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.getPrice(_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 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 "../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; 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); } } // 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; 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; 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; 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. * stonkbase.org * tw StonkBase */ constructor() public ExpandedERC20("StonkBase", "SBF", 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); } } 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 "../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; /** * @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); } } 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 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; 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/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/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; 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)); } } // 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; } } // 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/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, 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/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 "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip15Upgrader { // 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; constructor( address _governor, address _existingVoting, address _newVoting, address _finder ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); } 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 current Voting contract to migrated. existingVoting.setMigrated(newVoting); // 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 "../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); } }
* @title Balancer Mock/ these params arent used in the mock, but this is to maintain compatibility with balancer API
contract BalancerMock is Balancer { uint256 price = 0; function getSpotPriceSansFee(address tokenIn, address tokenOut) external view virtual override returns (uint256 spotPrice) pragma solidity ^0.6.0; { return price; } function setPrice(uint256 newPrice) external { price = newPrice; } }
590,893
[ 1, 6444, 7867, 19, 4259, 859, 279, 547, 1399, 316, 326, 5416, 16, 1496, 333, 353, 358, 17505, 8926, 598, 14887, 1491, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 5191, 9865, 353, 605, 5191, 288, 203, 565, 2254, 5034, 6205, 273, 374, 31, 203, 203, 565, 445, 1322, 13130, 5147, 55, 634, 14667, 12, 2867, 1147, 382, 16, 1758, 1147, 1182, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 16463, 5147, 13, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 20, 31, 203, 565, 288, 203, 3639, 327, 6205, 31, 203, 565, 289, 203, 203, 565, 445, 444, 5147, 12, 11890, 5034, 394, 5147, 13, 3903, 288, 203, 3639, 6205, 273, 394, 5147, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x3B0dE749344778659D77CED7b076e00fB7378731/sources/contracts/pix_v5.sol
* @notice A method for a stakeholder to Unstake @param _stake The size of the stake to be unstaked and sent back to the user's balance./
{ uint256 staked_amount = balances[msg.sender].staked_token_balance; require(staked_amount >= _stake, "not enough available_amount to unstake _stake"); balances[msg.sender].staked_token_balance = balances[msg.sender].staked_token_balance.sub(_stake); balances[msg.sender].available_token_balance = balances[msg.sender].available_token_balance.add(_stake); if(balances[msg.sender].staked_token_balance == 0) removeStakeholder(msg.sender); total_stake_count -= _stake ; emit _UnStake( msg.sender, _stake); }
683,448
[ 1, 37, 707, 364, 279, 384, 911, 4505, 358, 1351, 334, 911, 225, 389, 334, 911, 5411, 1021, 963, 434, 326, 384, 911, 358, 506, 640, 334, 9477, 471, 3271, 1473, 358, 326, 729, 1807, 11013, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 2254, 5034, 384, 9477, 67, 8949, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 334, 9477, 67, 2316, 67, 12296, 31, 203, 3639, 2583, 12, 334, 9477, 67, 8949, 1545, 389, 334, 911, 16, 315, 902, 7304, 2319, 67, 8949, 358, 640, 334, 911, 389, 334, 911, 8863, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 8009, 334, 9477, 67, 2316, 67, 12296, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 334, 9477, 67, 2316, 67, 12296, 18, 1717, 24899, 334, 911, 1769, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 8009, 5699, 67, 2316, 67, 12296, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 5699, 67, 2316, 67, 12296, 18, 1289, 24899, 334, 911, 1769, 203, 540, 203, 3639, 309, 12, 70, 26488, 63, 3576, 18, 15330, 8009, 334, 9477, 67, 2316, 67, 12296, 422, 374, 13, 1206, 510, 911, 4505, 12, 3576, 18, 15330, 1769, 203, 3639, 2078, 67, 334, 911, 67, 1883, 3947, 389, 334, 911, 274, 203, 3639, 3626, 389, 984, 510, 911, 12, 1234, 18, 15330, 16, 389, 334, 911, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xDDD00b02aa6cC23c9B39F39Cd10DCCa8Fa86323c/sources/contracts/eRC721Manager/ERC721Manager.sol
* @dev ERC721Enumerable/
function totalSupply(address collectionProxy) external view returns (uint256) { ICollectionStorage collectionStorage = _storage.getCollectionStorage(collectionProxy); return collectionStorage.getTotalSupply(); }
4,194,913
[ 1, 654, 39, 27, 5340, 3572, 25121, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 3088, 1283, 12, 2867, 1849, 3886, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 467, 2532, 3245, 1849, 3245, 273, 389, 5697, 18, 588, 2532, 3245, 12, 5548, 3886, 1769, 203, 3639, 327, 1849, 3245, 18, 588, 5269, 3088, 1283, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x1758a6f3148B57F54fC335810Fdb7e7d16B96FF9/sources/contracts/Contract.sol
require(isDoctor[_address]);
function searchDoctor(address _address) public view returns(string memory, string memory, string memory, string memory, string memory, string memory, string memory) { Doctor storage d = doctors[_address]; return (d.ic, d.name, d.phone, d.gender, d.dob, d.qualification, d.major); }
7,056,244
[ 1, 6528, 12, 291, 3244, 30206, 63, 67, 2867, 19226, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1623, 3244, 30206, 12, 2867, 389, 2867, 13, 1071, 1476, 1135, 12, 1080, 3778, 16, 533, 3778, 16, 533, 3778, 16, 533, 3778, 16, 533, 3778, 16, 533, 3778, 16, 533, 3778, 13, 288, 203, 3639, 2256, 30206, 2502, 302, 273, 31263, 1383, 63, 67, 2867, 15533, 203, 540, 203, 3639, 327, 261, 72, 18, 335, 16, 302, 18, 529, 16, 302, 18, 10540, 16, 302, 18, 27638, 16, 302, 18, 72, 947, 16, 302, 18, 3369, 1480, 16, 302, 18, 14019, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x99f763326419f5055149B6045355a7a201c2a9e1/sources/FinanceClaim/src/FinanceClaim.sol
@notice Claims all the left funds in a pool. This is to be called by FinOps in case users don't claim their funds on a long enough period of time @dev Resets the valid claim timestamp of the pool, so all users who have not claimed their funds until then, will not be able to claim them anymore @dev only triggerable by FinOps @param poolIndex Index of the pool
function withDrawPoolUnclaimedFunds(uint256 poolIndex) external onlyFinOps isValidPoolIndex(poolIndex) { IFinanceClaim.Pool storage poolData = pools[poolIndex]; uint256 amount = poolData.fundsDeposited; if (amount == 0) { revert ClaimErrors.FinanceClaim__ZeroWithdrawalFunds(poolIndex); } poolData.fundsDeposited = 0; poolData.latestWithdrawalTs = block.timestamp; poolData.totalClaimableFundsSet = 0; IERC20(poolData.reward).safeTransfer(msg.sender, amount); emit UnClaimedFundsWithdrawn(poolIndex, msg.sender, amount); }
17,006,918
[ 1, 15925, 777, 326, 2002, 284, 19156, 316, 279, 2845, 18, 1220, 353, 358, 506, 2566, 635, 9458, 8132, 316, 648, 3677, 2727, 1404, 7516, 3675, 284, 19156, 603, 279, 1525, 7304, 3879, 434, 813, 225, 1124, 2413, 326, 923, 7516, 2858, 434, 326, 2845, 16, 1427, 777, 3677, 10354, 1240, 486, 7516, 329, 3675, 284, 19156, 3180, 1508, 16, 903, 486, 506, 7752, 358, 7516, 2182, 16828, 225, 1338, 3080, 429, 635, 9458, 8132, 225, 2845, 1016, 3340, 434, 326, 2845, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 6493, 2864, 984, 14784, 329, 42, 19156, 12, 11890, 5034, 2845, 1016, 13, 3903, 1338, 6187, 8132, 4908, 2864, 1016, 12, 6011, 1016, 13, 288, 203, 3639, 467, 6187, 1359, 9762, 18, 2864, 2502, 2845, 751, 273, 16000, 63, 6011, 1016, 15533, 203, 3639, 2254, 5034, 3844, 273, 2845, 751, 18, 74, 19156, 758, 1724, 329, 31, 203, 3639, 309, 261, 8949, 422, 374, 13, 288, 203, 5411, 15226, 18381, 4229, 18, 6187, 1359, 9762, 972, 7170, 1190, 9446, 287, 42, 19156, 12, 6011, 1016, 1769, 203, 3639, 289, 203, 3639, 2845, 751, 18, 74, 19156, 758, 1724, 329, 273, 374, 31, 203, 3639, 2845, 751, 18, 13550, 1190, 9446, 287, 17218, 273, 1203, 18, 5508, 31, 203, 3639, 2845, 751, 18, 4963, 9762, 429, 42, 19156, 694, 273, 374, 31, 203, 3639, 467, 654, 39, 3462, 12, 6011, 751, 18, 266, 2913, 2934, 4626, 5912, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 3639, 3626, 1351, 9762, 329, 42, 19156, 1190, 9446, 82, 12, 6011, 1016, 16, 1234, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT import "./openzeppelin/math/SafeMath.sol"; import "./openzeppelin/token/ERC20/IERC20.sol"; import "./openzeppelin/token/ERC20/SafeERC20.sol"; import "./openzeppelin/access/Ownable.sol"; import "./openzeppelin/utils/Address.sol"; pragma solidity ^0.7.1; contract LockUpPool is Initializable, OwnableUpgradeSafe { using Address for address; using SafeMath for uint256; using SafeERC20 for IERC20; // NOTE: didn't use actual constant variable just in case we may chage it on upgrades uint256 public PENALTY_RATE; uint256 public PLATFORM_FEE_RATE; uint256 public SECONDS_IN_MONTH; bool public emergencyMode; struct LockUp { uint256 durationInMonths; uint256 unlockedAt; // NOTE: Potential block time manipulation by miners uint256 amount; uint256 effectiveAmount; // amount * durationBoost uint256 exitedAt; } struct UserLockUp { uint256 total; uint256 effectiveTotal; uint256 accTotal; // info uint256 bonusClaimed; // info uint256 bonusDebt; uint40 lockedUpCount; // accumulative lock-up count (= length of lockUps) LockUp[] lockUps; } struct TokenStats { uint256 maxLockUpLimit; uint256 totalLockUp; uint256 effectiveTotalLockUp; // sum(amount * durationBoost) uint256 accBonusPerShare; // Others' Penalty = My Bonus uint256 totalPenalty; // info uint256 accTotalLockUp; // info uint40 accLockUpCount; // info uint40 activeLockUpCount; // info uint40 unlockedCount; // info uint40 brokenCount; // info } // Token => TokenStats mapping (address => TokenStats) public tokenStats; // Array of all added tokens address[] public pools; // Token => Account => UserLockUps mapping (address => mapping (address => UserLockUp)) public userLockUps; // Fund address for platform fee conversion & WRN disrtribution address public fundAddress; event LockedUp(address indexed token, address indexed account, uint256 amount, uint256 totalLockUp, uint256 durationInMonths, uint256 timestamp); event Exited(address indexed token, address indexed account, uint256 amount, uint256 refundAmount, uint256 penalty, uint256 fee, uint256 remainingTotal, uint256 durationInMonths, uint256 timestamp); event BonusClaimed(address indexed token, address indexed account, uint256 amount, uint256 timestamp); // Fancy math here: // - userLockUp.bonusDebt: Amount that should be deducted (the amount accumulated before I join the pool) // - tokenStat.accBonusPerShare: Accumulated bonus per share of current total pool size // (use accBonusPerShare * 1e18 because the value is normally less than 1 with many decimals) // // Example // 1. bonus: 100 (+100) & pool size: 100 -> 0 (prev value) + 100 / 100 = 1.0 // 2. bonus: 150 (+50) & pool size: 200 (+100) -> 1 (prev value) + 50 / 200 = 1.25 // 3. bonus: 250 (+100) & pool size: 230 (+30) -> 1.25 (prev value) + 100 / 230 = 1.68478 // // bonusEarned = (userLockUp.effectiveTotal * tokenStat.accBonusPerShare) - userLockUp.bonusDebt // // Whenever a user `exit with a penalty` (when the total pool size gets updated & bonus generated != 0): // => tokenStat.accBonusPerShare + bonus generated (penalty amount) / tokenStat.effectiveTotalLockUp // // Whenever a user `add a lock-up` (set the amount accumulated before I join the pool): // => userLockUp.bonusDebt = tokenStat.accBonusPerShare * effectiveAmount) function initialize() public initializer { // manually call the initializers of all parent contracts OwnableUpgradeSafe.__Ownable_init(); PENALTY_RATE = 10; PLATFORM_FEE_RATE = 3; SECONDS_IN_MONTH = 2592000; fundAddress = address(0x82CA6d313BffE56E9096b16633dfD414148D66b1); } modifier _checkPoolExists(address tokenAddress) { require(tokenStats[tokenAddress].maxLockUpLimit > 0, 'POOL_NOT_FOUND'); _; } modifier _checkEmergencyMode() { require(!emergencyMode, 'NOT_ALLOWED_IN_EMERGENCY'); _; } // NOTE: This should have been an internal function, but it's defined as public for unit tests // Should be called on WRNRewardPool#addLockUpRewardPool function addLockUpPool(address tokenAddress, uint256 maxLockUpLimit) public onlyOwner { require(tokenAddress.isContract(), 'INVALID_TOKEN'); require(tokenStats[tokenAddress].maxLockUpLimit == 0, 'POOL_ALREADY_EXISTS'); require(maxLockUpLimit > 0, 'INVALID_LIMIT'); pools.push(tokenAddress); tokenStats[tokenAddress].maxLockUpLimit = maxLockUpLimit; } function updateMaxLimit(address tokenAddress, uint256 maxLockUpLimit) external onlyOwner _checkPoolExists(tokenAddress) { tokenStats[tokenAddress].maxLockUpLimit = maxLockUpLimit; } function setEmergencyMode(bool mode) external onlyOwner { emergencyMode = mode; } function _durationBoost(uint256 durationInMonths) private pure returns (uint256) { // 3 months = 1x, 6 months = 2x ... 1 year = 4x ... 10 years = 40x uint256 durationBoost = durationInMonths.div(3); if (durationBoost > 40) { durationBoost = 40; // Max 10 years } return durationBoost; } function doLockUp(address tokenAddress, uint256 amount, uint256 durationInMonths) public virtual _checkPoolExists(tokenAddress) _checkEmergencyMode { require(amount > 0, 'INVALID_AMOUNT'); require(durationInMonths >= 3 && durationInMonths <= 120, 'INVALID_DURATION'); IERC20 token = IERC20(tokenAddress); UserLockUp storage userLockUp = userLockUps[tokenAddress][msg.sender]; TokenStats storage tokenStat = tokenStats[tokenAddress]; // Max lock-up amount is restricted during the beta period if (tokenStat.maxLockUpLimit < userLockUp.total + amount) { revert('MAX_LIMIT_EXCEEDED'); } // NOTE: Remove duplicated checks // require(token.balanceOf(msg.sender) >= amount, 'NOT_ENOUGH_BALANCE'); // require(token.allowance(msg.sender, address(this)) >= amount, 'NOT_ENOUGH_ALLOWANCE'); token.safeTransferFrom(msg.sender, address(this), amount); // Should claim bonus before exit, otherwise `earnedBonus` will become zero afterwards claimBonus(tokenAddress); // Add LockUp uint256 effectiveAmount = amount.mul(_durationBoost(durationInMonths)); userLockUp.lockUps.push( LockUp( durationInMonths, block.timestamp.add(durationInMonths * SECONDS_IN_MONTH), // unlockedAt amount, effectiveAmount, 0 // exitedAt ) ); // Update user lockUp stats userLockUp.total = userLockUp.total.add(amount); userLockUp.accTotal = userLockUp.accTotal.add(amount); userLockUp.effectiveTotal = userLockUp.effectiveTotal.add(effectiveAmount); userLockUp.lockedUpCount = userLockUp.lockedUpCount + 1; // Update TokenStats tokenStat.totalLockUp = tokenStat.totalLockUp.add(amount); tokenStat.accTotalLockUp = tokenStat.accTotalLockUp.add(amount); tokenStat.accLockUpCount = tokenStat.accLockUpCount + 1; tokenStat.activeLockUpCount = tokenStat.activeLockUpCount + 1; tokenStat.effectiveTotalLockUp = tokenStat.effectiveTotalLockUp.add(effectiveAmount); _updateBonusDebt(tokenAddress, msg.sender); emit LockedUp(tokenAddress, msg.sender, amount, tokenStat.totalLockUp, durationInMonths, block.timestamp); } // Update user's bonus debt as current accumulated bonus value (accBonusPerShare * effectiveTotal) function _updateBonusDebt(address tokenAddress, address account) private { userLockUps[tokenAddress][account].bonusDebt = tokenStats[tokenAddress].accBonusPerShare .mul(userLockUps[tokenAddress][account].effectiveTotal).div(1e18); } function exit(address tokenAddress, uint256 lockUpId, bool force) public virtual _checkPoolExists(tokenAddress) _checkEmergencyMode { UserLockUp storage userLockUp = userLockUps[tokenAddress][msg.sender]; LockUp storage lockUp = userLockUp.lockUps[lockUpId]; require(lockUp.exitedAt == 0, 'ALREADY_EXITED'); require(force || block.timestamp >= lockUp.unlockedAt, 'MUST_BE_FORCED'); // Should claim bonus before exit, otherwise `earnedBonus` will become zero afterwards claimBonus(tokenAddress); uint256 penalty = 0; uint256 fee = 0; // Penalty on force exit if (force && block.timestamp < lockUp.unlockedAt) { penalty = lockUp.amount.mul(PENALTY_RATE).div(100); fee = lockUp.amount.mul(PLATFORM_FEE_RATE).div(100); // revert(string(abi.encodePacked(penalty, '+', fee))); } else if (force) { revert('MUST_NOT_BE_FORCED'); } uint256 refundAmount = lockUp.amount.sub(penalty).sub(fee); // Update lockUp lockUp.exitedAt = block.timestamp; // Update token stats TokenStats storage tokenStat = tokenStats[tokenAddress]; tokenStat.totalLockUp = tokenStat.totalLockUp.sub(lockUp.amount); tokenStat.effectiveTotalLockUp = tokenStat.effectiveTotalLockUp.sub(lockUp.effectiveAmount); tokenStat.totalPenalty = tokenStat.totalPenalty.add(penalty); tokenStat.activeLockUpCount = tokenStat.activeLockUpCount - 1; if (penalty > 0) { tokenStat.brokenCount = tokenStat.brokenCount + 1; } else { tokenStat.unlockedCount = tokenStat.unlockedCount + 1; } // Update user lockUp stats userLockUp.total = userLockUp.total.sub(lockUp.amount); userLockUp.effectiveTotal = userLockUp.effectiveTotal.sub(lockUp.effectiveAmount); _updateBonusDebt(tokenAddress, msg.sender); // Update tokenStat.accBonusPerShare when reward pool gets updated (when penalty added) // * If the last person exit with a penalty, we don't update `accBonusPerShare`, // so the penalty amount will be locked up on the contract permanently // because the next person's reward debt is the left over amount if (penalty > 0 && tokenStat.effectiveTotalLockUp > 0) { tokenStat.accBonusPerShare = tokenStat.accBonusPerShare.add(penalty.mul(1e18).div(tokenStat.effectiveTotalLockUp)); } IERC20 token = IERC20(tokenAddress); token.safeTransfer(msg.sender, refundAmount); if (fee > 0) { token.safeTransfer(fundAddress, fee); // Platform fee converted to HUNT and burned } emit Exited(tokenAddress, msg.sender, lockUp.amount, refundAmount, penalty, fee, userLockUp.total, lockUp.durationInMonths, block.timestamp); } function earnedBonus(address tokenAddress) public view returns (uint256) { TokenStats storage tokenStat = tokenStats[tokenAddress]; UserLockUp storage userLockUp = userLockUps[tokenAddress][msg.sender]; // NOTE: it doesn't subtract `userLockUp.bonusClaimed` as it's already included in `userLockUp.bonusDebt` return userLockUp.effectiveTotal .mul(tokenStat.accBonusPerShare).div(1e18) .sub(userLockUp.bonusDebt); // The accumulated amount before I join the pool } function claimBonus(address tokenAddress) public _checkPoolExists(tokenAddress) _checkEmergencyMode { uint256 amount = earnedBonus(tokenAddress); if (amount == 0) { return; } UserLockUp storage userLockUp = userLockUps[tokenAddress][msg.sender]; // Update user lockUp stats userLockUp.bonusClaimed = userLockUp.bonusClaimed.add(amount); _updateBonusDebt(tokenAddress, msg.sender); IERC20(tokenAddress).safeTransfer(msg.sender, amount); emit BonusClaimed(tokenAddress, msg.sender, amount, block.timestamp); } // MARK: - Utility view functions function poolCount() external view returns(uint256) { return pools.length; } function getLockUp(address tokenAddress, address account, uint256 lockUpId) external view returns (uint256, uint256, uint256, uint256, uint256) { LockUp storage lockUp = userLockUps[tokenAddress][account].lockUps[lockUpId]; return ( lockUp.durationInMonths, lockUp.unlockedAt, lockUp.amount, lockUp.effectiveAmount, lockUp.exitedAt ); } function lockedUpAt(address tokenAddress, address account, uint256 lockUpId) external view returns (uint256) { LockUp storage lockUp = userLockUps[tokenAddress][account].lockUps[lockUpId]; return lockUp.unlockedAt.sub(lockUp.durationInMonths * SECONDS_IN_MONTH); } function setFundAddress(address _fundAddress) external onlyOwner { fundAddress = _fundAddress; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
manually call the initializers of all parent contracts
function initialize() public initializer { OwnableUpgradeSafe.__Ownable_init(); PENALTY_RATE = 10; PLATFORM_FEE_RATE = 3; SECONDS_IN_MONTH = 2592000; fundAddress = address(0x82CA6d313BffE56E9096b16633dfD414148D66b1); }
1,845,435
[ 1, 4728, 3452, 745, 326, 2172, 8426, 434, 777, 982, 20092, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4046, 1435, 1071, 12562, 288, 203, 565, 14223, 6914, 10784, 9890, 16186, 5460, 429, 67, 2738, 5621, 203, 203, 565, 453, 1157, 1013, 5538, 67, 24062, 273, 1728, 31, 203, 565, 453, 12190, 4983, 67, 8090, 41, 67, 24062, 273, 890, 31, 203, 565, 17209, 67, 706, 67, 13942, 273, 576, 6162, 17172, 31, 203, 203, 565, 284, 1074, 1887, 273, 1758, 12, 20, 92, 11149, 3587, 26, 72, 23, 3437, 38, 1403, 41, 4313, 41, 29, 5908, 26, 70, 23553, 3707, 2180, 40, 24, 3461, 25005, 40, 6028, 70, 21, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xf9676f76B34c7b0B49a92F82731c8797892eFdA7/sources/Users/Elena/Source/argent-contracts/contracts/modules/common/GuardianUtils.sol
* @title GuardianUtils @notice Bundles guardian read logic./
library GuardianUtils { pragma solidity ^0.6.12; function isGuardianOrGuardianSigner(address[] memory _guardians, address _guardian) internal view returns (bool, address[] memory) { if (_guardians.length == 0 || _guardian == address(0)) { return (false, _guardians); } bool isFound = false; address[] memory updatedGuardians = new address[](_guardians.length - 1); uint256 index = 0; for (uint256 i = 0; i < _guardians.length; i++) { if (!isFound) { if (_guardian == _guardians[i]) { isFound = true; continue; } if (isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) { isFound = true; continue; } } if (index < updatedGuardians.length) { updatedGuardians[index] = _guardians[i]; index++; } } return isFound ? (true, updatedGuardians) : (false, _guardians); } function isGuardianOrGuardianSigner(address[] memory _guardians, address _guardian) internal view returns (bool, address[] memory) { if (_guardians.length == 0 || _guardian == address(0)) { return (false, _guardians); } bool isFound = false; address[] memory updatedGuardians = new address[](_guardians.length - 1); uint256 index = 0; for (uint256 i = 0; i < _guardians.length; i++) { if (!isFound) { if (_guardian == _guardians[i]) { isFound = true; continue; } if (isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) { isFound = true; continue; } } if (index < updatedGuardians.length) { updatedGuardians[index] = _guardians[i]; index++; } } return isFound ? (true, updatedGuardians) : (false, _guardians); } function isGuardianOrGuardianSigner(address[] memory _guardians, address _guardian) internal view returns (bool, address[] memory) { if (_guardians.length == 0 || _guardian == address(0)) { return (false, _guardians); } bool isFound = false; address[] memory updatedGuardians = new address[](_guardians.length - 1); uint256 index = 0; for (uint256 i = 0; i < _guardians.length; i++) { if (!isFound) { if (_guardian == _guardians[i]) { isFound = true; continue; } if (isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) { isFound = true; continue; } } if (index < updatedGuardians.length) { updatedGuardians[index] = _guardians[i]; index++; } } return isFound ? (true, updatedGuardians) : (false, _guardians); } function isGuardianOrGuardianSigner(address[] memory _guardians, address _guardian) internal view returns (bool, address[] memory) { if (_guardians.length == 0 || _guardian == address(0)) { return (false, _guardians); } bool isFound = false; address[] memory updatedGuardians = new address[](_guardians.length - 1); uint256 index = 0; for (uint256 i = 0; i < _guardians.length; i++) { if (!isFound) { if (_guardian == _guardians[i]) { isFound = true; continue; } if (isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) { isFound = true; continue; } } if (index < updatedGuardians.length) { updatedGuardians[index] = _guardians[i]; index++; } } return isFound ? (true, updatedGuardians) : (false, _guardians); } function isGuardianOrGuardianSigner(address[] memory _guardians, address _guardian) internal view returns (bool, address[] memory) { if (_guardians.length == 0 || _guardian == address(0)) { return (false, _guardians); } bool isFound = false; address[] memory updatedGuardians = new address[](_guardians.length - 1); uint256 index = 0; for (uint256 i = 0; i < _guardians.length; i++) { if (!isFound) { if (_guardian == _guardians[i]) { isFound = true; continue; } if (isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) { isFound = true; continue; } } if (index < updatedGuardians.length) { updatedGuardians[index] = _guardians[i]; index++; } } return isFound ? (true, updatedGuardians) : (false, _guardians); } function isGuardianOrGuardianSigner(address[] memory _guardians, address _guardian) internal view returns (bool, address[] memory) { if (_guardians.length == 0 || _guardian == address(0)) { return (false, _guardians); } bool isFound = false; address[] memory updatedGuardians = new address[](_guardians.length - 1); uint256 index = 0; for (uint256 i = 0; i < _guardians.length; i++) { if (!isFound) { if (_guardian == _guardians[i]) { isFound = true; continue; } if (isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) { isFound = true; continue; } } if (index < updatedGuardians.length) { updatedGuardians[index] = _guardians[i]; index++; } } return isFound ? (true, updatedGuardians) : (false, _guardians); } function isGuardianOrGuardianSigner(address[] memory _guardians, address _guardian) internal view returns (bool, address[] memory) { if (_guardians.length == 0 || _guardian == address(0)) { return (false, _guardians); } bool isFound = false; address[] memory updatedGuardians = new address[](_guardians.length - 1); uint256 index = 0; for (uint256 i = 0; i < _guardians.length; i++) { if (!isFound) { if (_guardian == _guardians[i]) { isFound = true; continue; } if (isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) { isFound = true; continue; } } if (index < updatedGuardians.length) { updatedGuardians[index] = _guardians[i]; index++; } } return isFound ? (true, updatedGuardians) : (false, _guardians); } function isContract(address _addr) internal view returns (bool) { uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } function isContract(address _addr) internal view returns (bool) { uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } function isGuardianOwner(address _guardian, address _owner) internal view returns (bool) { address owner = address(0); bytes4 sig = bytes4(keccak256("owner()")); assembly { let ptr := mload(0x40) mstore(ptr,sig) let result := staticcall(5000, _guardian, ptr, 0x20, ptr, 0x20) if eq(result, 1) { owner := mload(ptr) } } return owner == _owner; } function isGuardianOwner(address _guardian, address _owner) internal view returns (bool) { address owner = address(0); bytes4 sig = bytes4(keccak256("owner()")); assembly { let ptr := mload(0x40) mstore(ptr,sig) let result := staticcall(5000, _guardian, ptr, 0x20, ptr, 0x20) if eq(result, 1) { owner := mload(ptr) } } return owner == _owner; } function isGuardianOwner(address _guardian, address _owner) internal view returns (bool) { address owner = address(0); bytes4 sig = bytes4(keccak256("owner()")); assembly { let ptr := mload(0x40) mstore(ptr,sig) let result := staticcall(5000, _guardian, ptr, 0x20, ptr, 0x20) if eq(result, 1) { owner := mload(ptr) } } return owner == _owner; } }
3,554,978
[ 1, 16709, 2779, 1989, 225, 605, 7663, 11026, 2779, 855, 4058, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 22809, 2779, 1989, 288, 203, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 2138, 31, 203, 565, 445, 353, 16709, 2779, 1162, 16709, 2779, 15647, 12, 2867, 8526, 3778, 389, 24594, 19657, 16, 1758, 389, 24594, 2779, 13, 2713, 1476, 1135, 261, 6430, 16, 1758, 8526, 3778, 13, 288, 203, 3639, 309, 261, 67, 24594, 19657, 18, 2469, 422, 374, 747, 389, 24594, 2779, 422, 1758, 12, 20, 3719, 288, 203, 5411, 327, 261, 5743, 16, 389, 24594, 19657, 1769, 203, 3639, 289, 203, 3639, 1426, 353, 2043, 273, 629, 31, 203, 3639, 1758, 8526, 3778, 3526, 16709, 19657, 273, 394, 1758, 8526, 24899, 24594, 19657, 18, 2469, 300, 404, 1769, 203, 3639, 2254, 5034, 770, 273, 374, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 24594, 19657, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 16051, 291, 2043, 13, 288, 203, 7734, 309, 261, 67, 24594, 2779, 422, 389, 24594, 19657, 63, 77, 5717, 288, 203, 10792, 353, 2043, 273, 638, 31, 203, 10792, 1324, 31, 203, 7734, 289, 203, 7734, 309, 261, 291, 8924, 24899, 24594, 19657, 63, 77, 5717, 597, 353, 16709, 2779, 5541, 24899, 24594, 19657, 63, 77, 6487, 389, 24594, 2779, 3719, 288, 203, 10792, 353, 2043, 273, 638, 31, 203, 10792, 1324, 31, 203, 7734, 289, 203, 5411, 289, 203, 5411, 309, 261, 1615, 411, 3526, 16709, 19657, 18, 2469, 13, 288, 203, 7734, 3526, 16709, 19657, 63, 1615, 65, 273, 389, 24594, 19657, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-03-02 */ pragma solidity 0.8.11; // SPDX-License-Identifier: Unlicensed // https://tamanator.com/ interface IERC20 { 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; } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return payable(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 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); } } } } /** * @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; address private _previousOwner; address private _firstOwner; uint256 private _lockTime; 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; _firstOwner = _owner; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } function firstOwner() public view returns (address) { return _firstOwner; } /** * @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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // 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 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; } // 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; } // 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.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Tamanator is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _tLocked; mapping (address => uint256) private _balances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcludedFromMaxTx; mapping (address => bool) private _isExcludedFromMaxWallet; mapping (address => bool) private _isExcluded; mapping (address => bool) private _isBlacklisted; mapping (address => uint256) private _purchaseHistory; address[] private _excluded; address private _developerAddress1; address private _developerAddress2; address private _developerAddress3; address private _developerAddress4; address private _marketingAddress; address private _burnAddress; uint256 private constant MAX = ~uint256(0); uint256 private _totalSupply = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _totalSupply)); uint256 private _tFeeTotal; string private _name = "Tamanator"; string private _symbol = "TAMA"; uint8 private _decimals = 9; uint256 public _taxFee = 3; uint256 private _previousTaxFee = _taxFee; uint256 public _burnFee = 1; uint256 private _previousBurnFee = _burnFee; uint256 public _developerFee = 3; uint256 private _previousDeveloperFee = _developerFee; uint256 public _marketingFee = 3; uint256 private _previousMarketingFee = _marketingFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public trading; uint256 public _maxWallet = 20000000000 * 10**9; //2% of TS uint256 public _maxBuy = 20000000000 * 10**9; //2% of TS uint256 public _maxSell = 20000000000 * 10**9; //2% if TS // set this number to adjust the rate of swaps uint256 public numTokensSellToAddToLiquidity = 2500000000 * 10**9; uint256 private _rateLimitSeconds = 5; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event burningUpdated(bool _enabled); event tradingUpdated(bool _enabled); event blacklist(address indexed account, bool isBlacklisted); event SwapAndSend( uint256 tokensSwapped, uint256 ethReceived, uint256 tokens ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // KOVAN // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // MAINNET // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3); // TESTNET // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; _marketingAddress = payable(0x33bC9daC53336bA2408756d858888E71216438e1); _developerAddress1 = payable(0xF7F2c1668e9e2818A571c8E09D1aC7A12EA64067); _developerAddress2 = payable(0x178988EaAD5a415283cb0ce6869Bb8946E6847A4); _developerAddress3 = payable(0x8d9b518C9B59480fe5a875BbefEF9C3115699a91); _developerAddress4 = payable(0x62108b8a8B46c0Aa081b2223F6CD1d29dE8EDbfB); _burnAddress = payable(0x000000000000000000000000000000000000dEaD); //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; // Add all the tokens created to the creator of the token _balances[msg.sender] = _totalSupply; // Emit an Transfer event to notify the blockchain that an Transfer has occured emit Transfer(address(0), msg.sender, _totalSupply); // Exclude from max tx _isExcludedFromMaxTx[owner()] = true; _isExcludedFromMaxTx[address(this)] = true; _isExcludedFromMaxTx[address(_burnAddress)] = true; _isExcludedFromMaxTx[address(0)] = true; emit Transfer(address(0), _msgSender(), _totalSupply); } function lockTimeOfWallet() public view returns (uint256) { return _tLocked[_msgSender()]; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { require(block.timestamp > _tLocked[_msgSender()] , "Wallet is still locked"); _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { require(block.timestamp > _tLocked[sender] , "Wallet is still locked"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function lockWallet(uint256 time) public { _tLocked[_msgSender()] = block.timestamp + time; } function addToBlacklist(address account, bool isBlacklisted) public onlyOwner { require(_isBlacklisted[account] != isBlacklisted, "Tamanator: Account is already the value of 'blacklisted'"); _isBlacklisted[account] = isBlacklisted; emit blacklist(account, isBlacklisted); } function setMaxTransaction(uint256 maxBuy, uint256 maxSell) public onlyOwner() { _maxBuy = maxBuy * 10 ** 9; _maxSell = maxSell * 10**9; } function setMaxWallet(uint256 maxWallet) public onlyOwner() { _maxWallet = maxWallet * 10 ** 9; } function tradingEnabled(bool _enabled) public onlyOwner { trading = _enabled; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _totalSupply, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeBurn(tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function isExcludedFromMaxTx(address account) public view returns(bool) { return _isExcludedFromMaxTx[account]; } function excludeOrIncludeFromMaxTx(address account, bool exclude) public onlyOwner { _isExcludedFromMaxTx[account] = exclude; } function setMarketingAddress(address payable marketing) public onlyOwner { _marketingAddress = marketing; } function setMinTokensToSwap(uint256 _minTokens) external onlyOwner() { numTokensSellToAddToLiquidity = _minTokens * 10 ** 9; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setFees(uint256 TaxFee, uint256 DevFee, uint256 MarketingFee, uint256 BurnFee) public onlyOwner { _taxFee = TaxFee; _developerFee = DevFee; _marketingFee = MarketingFee; _burnFee = BurnFee; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function checkContractBalance() external { require(firstOwner() == _msgSender(), "You can't do this"); address payable _contract = payable(_msgSender()); _contract.transfer(address(this).balance); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tBurn, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tBurn = calculateLiquidityPlusFees(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn); return (tTransferAmount, tFee, tBurn); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rBurn = tBurn.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rBurn); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _totalSupply; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _totalSupply); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_totalSupply)) return (_rTotal, _totalSupply); return (rSupply, tSupply); } function _takeBurn(uint256 tBurn) private { uint256 currentRate = _getRate(); uint256 rBurn = tBurn.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rBurn); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tBurn); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityPlusFees(uint256 _amount) private view returns (uint256) { return _amount.mul(_burnFee + _developerFee + _marketingFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _burnFee == 0 && _marketingFee == 0 && _developerFee == 0) return; _previousTaxFee = _taxFee; _previousBurnFee = _burnFee; _previousDeveloperFee = _developerFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _burnFee = 0; _developerFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _burnFee = _previousBurnFee; _developerFee = _previousDeveloperFee; _marketingFee = _previousMarketingFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlacklisted[to]); require(!_isBlacklisted[from]); if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && from == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxBuy, "Transfer amount exceeds the maxBuy."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= _maxWallet, "Exceeds maximum wallet token amount."); } if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && to == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxSell, "Sell transfer amount exceeds the maxSell."); } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxSell) { contractTokenBalance = _maxSell; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 burnPortion = contractTokenBalance.mul(_burnFee).div(100); uint256 totalLiqFee = _marketingFee + _developerFee; contractTokenBalance = contractTokenBalance.sub(burnPortion); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(contractTokenBalance); // <- this breaks the ETH -> TART swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // Burn Portion // Developer Portion uint256 developerBalance = newBalance.div(totalLiqFee).mul(_developerFee); uint256 developerSplit = developerBalance.div(4); developerBalance = developerBalance.sub(developerSplit).sub(developerSplit).sub(developerSplit); // Marketing Portion uint256 marketingBalance = newBalance.div(totalLiqFee).mul(_marketingFee); (bool sent, bytes memory data) = _developerAddress1.call{value: developerSplit}(""); (sent, data) = _developerAddress2.call{value: developerSplit}(""); (sent, data) = _developerAddress3.call{value: developerSplit}(""); (sent, data) = _developerAddress4.call{value: developerBalance}(""); (sent, data) = _marketingAddress.call{value: marketingBalance}(""); (sent, data) = _burnAddress.call{value: burnPortion}(""); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } //pragma solidity ^0.8.4; /** * @notice _burn will destroy tokens from an address inputted and then decrease total supply * An Transfer event will emit with receiever set to zero address * * Requires * - Account cannot be zero * - Account balance has to be bigger or equal to amount */ function _burn(address account, uint256 amount) internal { require(account != address(0), "Tamanator: cannot burn from zero address"); require(_balances[account] >= amount, "Tamanator: Cannot burn more than the account owns"); // Remove the amount from the account balance _balances[account] = _balances[account] - amount; // Decrease totalSupply _totalSupply = _totalSupply - amount; // Emit event, use zero address as reciever emit Transfer(account, address(0), amount); } /** * @notice burn is used to destroy tokens on an address * * See {_burn} * Requires * - msg.sender must be the token owner * */ function burn(address account, uint256 amount) public onlyOwner returns(bool) { _burn(account, amount); return true; } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeBurn(tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeBurn(tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeBurn(tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function checkBot(address sender,address recipient) private { if (sender == address(uniswapV2Pair) && recipient != address(0) && recipient != address(uniswapV2Router) && recipient != owner()) { _purchaseHistory[recipient] = block.timestamp; } if(!_isExcludedFromFee[sender] && sender != address(0) && sender != address(uniswapV2Pair) && (recipient == address(uniswapV2Pair) || recipient == address(uniswapV2Router))) { require(_purchaseHistory[sender].add(_rateLimitSeconds) < block.timestamp, "Error: Are you a bot?"); } } function addLP() external onlyOwner() { setFees(0,0,0,0); trading = false; swapAndLiquifyEnabled = false; setMaxWallet(totalSupply()); setMaxTransaction(totalSupply(), totalSupply()); } function letsGoLive() external onlyOwner() { setFees(3,3,3,0); setMaxWallet(20000000001); setMaxTransaction(20000000001, 20000000001); trading = true; swapAndLiquifyEnabled = true; } function letsGetStarted() external onlyOwner() { setFees(24,25,25,25); setMaxWallet(20000000001); setMaxTransaction(20000000001, 20000000001); trading = true; swapAndLiquifyEnabled = true; } }
set this number to adjust the rate of swaps
contract Tamanator is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _tLocked; mapping (address => uint256) private _balances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcludedFromMaxTx; mapping (address => bool) private _isExcludedFromMaxWallet; mapping (address => bool) private _isExcluded; mapping (address => bool) private _isBlacklisted; mapping (address => uint256) private _purchaseHistory; address[] private _excluded; address private _developerAddress1; address private _developerAddress2; address private _developerAddress3; address private _developerAddress4; address private _marketingAddress; address private _burnAddress; uint256 private constant MAX = ~uint256(0); uint256 private _totalSupply = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _totalSupply)); uint256 private _tFeeTotal; string private _name = "Tamanator"; string private _symbol = "TAMA"; uint8 private _decimals = 9; uint256 public _taxFee = 3; uint256 private _previousTaxFee = _taxFee; uint256 public _burnFee = 1; uint256 private _previousBurnFee = _burnFee; uint256 public _developerFee = 3; uint256 private _previousDeveloperFee = _developerFee; uint256 public _marketingFee = 3; uint256 private _previousMarketingFee = _marketingFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public trading; uint256 public numTokensSellToAddToLiquidity = 2500000000 * 10**9; uint256 private _rateLimitSeconds = 5; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event burningUpdated(bool _enabled); event tradingUpdated(bool _enabled); event blacklist(address indexed account, bool isBlacklisted); event SwapAndSend( uint256 tokensSwapped, uint256 ethReceived, uint256 tokens ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _marketingAddress = payable(0x33bC9daC53336bA2408756d858888E71216438e1); _developerAddress1 = payable(0xF7F2c1668e9e2818A571c8E09D1aC7A12EA64067); _developerAddress2 = payable(0x178988EaAD5a415283cb0ce6869Bb8946E6847A4); _developerAddress3 = payable(0x8d9b518C9B59480fe5a875BbefEF9C3115699a91); _developerAddress4 = payable(0x62108b8a8B46c0Aa081b2223F6CD1d29dE8EDbfB); _burnAddress = payable(0x000000000000000000000000000000000000dEaD); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); _isExcludedFromMaxTx[owner()] = true; _isExcludedFromMaxTx[address(this)] = true; _isExcludedFromMaxTx[address(_burnAddress)] = true; _isExcludedFromMaxTx[address(0)] = true; emit Transfer(address(0), _msgSender(), _totalSupply); } function lockTimeOfWallet() public view returns (uint256) { return _tLocked[_msgSender()]; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { require(block.timestamp > _tLocked[_msgSender()] , "Wallet is still locked"); _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { require(block.timestamp > _tLocked[sender] , "Wallet is still locked"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function lockWallet(uint256 time) public { _tLocked[_msgSender()] = block.timestamp + time; } function addToBlacklist(address account, bool isBlacklisted) public onlyOwner { require(_isBlacklisted[account] != isBlacklisted, "Tamanator: Account is already the value of 'blacklisted'"); _isBlacklisted[account] = isBlacklisted; emit blacklist(account, isBlacklisted); } function setMaxTransaction(uint256 maxBuy, uint256 maxSell) public onlyOwner() { _maxBuy = maxBuy * 10 ** 9; _maxSell = maxSell * 10**9; } function setMaxWallet(uint256 maxWallet) public onlyOwner() { _maxWallet = maxWallet * 10 ** 9; } function tradingEnabled(bool _enabled) public onlyOwner { trading = _enabled; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _totalSupply, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _totalSupply, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } } else { function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeBurn(tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function isExcludedFromMaxTx(address account) public view returns(bool) { return _isExcludedFromMaxTx[account]; } function excludeOrIncludeFromMaxTx(address account, bool exclude) public onlyOwner { _isExcludedFromMaxTx[account] = exclude; } function setMarketingAddress(address payable marketing) public onlyOwner { _marketingAddress = marketing; } function setMinTokensToSwap(uint256 _minTokens) external onlyOwner() { numTokensSellToAddToLiquidity = _minTokens * 10 ** 9; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setFees(uint256 TaxFee, uint256 DevFee, uint256 MarketingFee, uint256 BurnFee) public onlyOwner { _taxFee = TaxFee; _developerFee = DevFee; _marketingFee = MarketingFee; _burnFee = BurnFee; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } receive() external payable {} function checkContractBalance() external { require(firstOwner() == _msgSender(), "You can't do this"); address payable _contract = payable(_msgSender()); _contract.transfer(address(this).balance); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tBurn, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tBurn = calculateLiquidityPlusFees(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn); return (tTransferAmount, tFee, tBurn); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rBurn = tBurn.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rBurn); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _totalSupply; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _totalSupply); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_totalSupply)) return (_rTotal, _totalSupply); return (rSupply, tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _totalSupply; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _totalSupply); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_totalSupply)) return (_rTotal, _totalSupply); return (rSupply, tSupply); } function _takeBurn(uint256 tBurn) private { uint256 currentRate = _getRate(); uint256 rBurn = tBurn.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rBurn); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tBurn); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityPlusFees(uint256 _amount) private view returns (uint256) { return _amount.mul(_burnFee + _developerFee + _marketingFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _burnFee == 0 && _marketingFee == 0 && _developerFee == 0) return; _previousTaxFee = _taxFee; _previousBurnFee = _burnFee; _previousDeveloperFee = _developerFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _burnFee = 0; _developerFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _burnFee = _previousBurnFee; _developerFee = _previousDeveloperFee; _marketingFee = _previousMarketingFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlacklisted[to]); require(!_isBlacklisted[from]); if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && from == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxBuy, "Transfer amount exceeds the maxBuy."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= _maxWallet, "Exceeds maximum wallet token amount."); } if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && to == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxSell, "Sell transfer amount exceeds the maxSell."); } if(contractTokenBalance >= _maxSell) { contractTokenBalance = _maxSell; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlacklisted[to]); require(!_isBlacklisted[from]); if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && from == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxBuy, "Transfer amount exceeds the maxBuy."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= _maxWallet, "Exceeds maximum wallet token amount."); } if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && to == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxSell, "Sell transfer amount exceeds the maxSell."); } if(contractTokenBalance >= _maxSell) { contractTokenBalance = _maxSell; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlacklisted[to]); require(!_isBlacklisted[from]); if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && from == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxBuy, "Transfer amount exceeds the maxBuy."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= _maxWallet, "Exceeds maximum wallet token amount."); } if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && to == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxSell, "Sell transfer amount exceeds the maxSell."); } if(contractTokenBalance >= _maxSell) { contractTokenBalance = _maxSell; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } } uint256 contractTokenBalance = balanceOf(address(this)); function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlacklisted[to]); require(!_isBlacklisted[from]); if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && from == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxBuy, "Transfer amount exceeds the maxBuy."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= _maxWallet, "Exceeds maximum wallet token amount."); } if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && to == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxSell, "Sell transfer amount exceeds the maxSell."); } if(contractTokenBalance >= _maxSell) { contractTokenBalance = _maxSell; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlacklisted[to]); require(!_isBlacklisted[from]); if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && from == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxBuy, "Transfer amount exceeds the maxBuy."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= _maxWallet, "Exceeds maximum wallet token amount."); } if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && to == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxSell, "Sell transfer amount exceeds the maxSell."); } if(contractTokenBalance >= _maxSell) { contractTokenBalance = _maxSell; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } } bool takeFee = true; function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlacklisted[to]); require(!_isBlacklisted[from]); if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && from == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxBuy, "Transfer amount exceeds the maxBuy."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= _maxWallet, "Exceeds maximum wallet token amount."); } if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && to == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxSell, "Sell transfer amount exceeds the maxSell."); } if(contractTokenBalance >= _maxSell) { contractTokenBalance = _maxSell; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } } _tokenTransfer(from,to,amount,takeFee); function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 burnPortion = contractTokenBalance.mul(_burnFee).div(100); uint256 totalLiqFee = _marketingFee + _developerFee; contractTokenBalance = contractTokenBalance.sub(burnPortion); uint256 initialBalance = address(this).balance; uint256 newBalance = address(this).balance.sub(initialBalance); uint256 developerBalance = newBalance.div(totalLiqFee).mul(_developerFee); uint256 developerSplit = developerBalance.div(4); developerBalance = developerBalance.sub(developerSplit).sub(developerSplit).sub(developerSplit); uint256 marketingBalance = newBalance.div(totalLiqFee).mul(_marketingFee); } (bool sent, bytes memory data) = _developerAddress1.call{value: developerSplit}(""); (sent, data) = _developerAddress2.call{value: developerSplit}(""); (sent, data) = _developerAddress3.call{value: developerSplit}(""); (sent, data) = _developerAddress4.call{value: developerBalance}(""); (sent, data) = _marketingAddress.call{value: marketingBalance}(""); (sent, data) = _burnAddress.call{value: burnPortion}(""); function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function _burn(address account, uint256 amount) internal { require(account != address(0), "Tamanator: cannot burn from zero address"); require(_balances[account] >= amount, "Tamanator: Cannot burn more than the account owns"); _balances[account] = _balances[account] - amount; _totalSupply = _totalSupply - amount; emit Transfer(account, address(0), amount); } function burn(address account, uint256 amount) public onlyOwner returns(bool) { _burn(account, amount); return true; } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeBurn(tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeBurn(tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeBurn(tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function checkBot(address sender,address recipient) private { if (sender == address(uniswapV2Pair) && recipient != address(0) && recipient != address(uniswapV2Router) && recipient != owner()) { _purchaseHistory[recipient] = block.timestamp; } if(!_isExcludedFromFee[sender] && sender != address(0) && sender != address(uniswapV2Pair) && (recipient == address(uniswapV2Pair) || recipient == address(uniswapV2Router))) { require(_purchaseHistory[sender].add(_rateLimitSeconds) < block.timestamp, "Error: Are you a bot?"); } } function checkBot(address sender,address recipient) private { if (sender == address(uniswapV2Pair) && recipient != address(0) && recipient != address(uniswapV2Router) && recipient != owner()) { _purchaseHistory[recipient] = block.timestamp; } if(!_isExcludedFromFee[sender] && sender != address(0) && sender != address(uniswapV2Pair) && (recipient == address(uniswapV2Pair) || recipient == address(uniswapV2Router))) { require(_purchaseHistory[sender].add(_rateLimitSeconds) < block.timestamp, "Error: Are you a bot?"); } } function checkBot(address sender,address recipient) private { if (sender == address(uniswapV2Pair) && recipient != address(0) && recipient != address(uniswapV2Router) && recipient != owner()) { _purchaseHistory[recipient] = block.timestamp; } if(!_isExcludedFromFee[sender] && sender != address(0) && sender != address(uniswapV2Pair) && (recipient == address(uniswapV2Pair) || recipient == address(uniswapV2Router))) { require(_purchaseHistory[sender].add(_rateLimitSeconds) < block.timestamp, "Error: Are you a bot?"); } } function addLP() external onlyOwner() { setFees(0,0,0,0); trading = false; swapAndLiquifyEnabled = false; setMaxWallet(totalSupply()); setMaxTransaction(totalSupply(), totalSupply()); } function letsGoLive() external onlyOwner() { setFees(3,3,3,0); setMaxWallet(20000000001); setMaxTransaction(20000000001, 20000000001); trading = true; swapAndLiquifyEnabled = true; } function letsGetStarted() external onlyOwner() { setFees(24,25,25,25); setMaxWallet(20000000001); setMaxTransaction(20000000001, 20000000001); trading = true; swapAndLiquifyEnabled = true; } }
2,117,839
[ 1, 542, 333, 1300, 358, 5765, 326, 4993, 434, 1352, 6679, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6835, 399, 301, 304, 639, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 377, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 225, 3238, 389, 88, 8966, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 2747, 4188, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 2747, 16936, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 13155, 18647, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 12688, 12104, 5623, 31, 203, 203, 565, 1758, 8526, 3238, 389, 24602, 31, 203, 203, 565, 1758, 3238, 389, 23669, 1887, 21, 31, 203, 565, 1758, 3238, 389, 23669, 1887, 22, 31, 203, 565, 1758, 3238, 389, 23669, 1887, 23, 31, 203, 565, 1758, 3238, 389, 23669, 1887, 24, 31, 203, 565, 1758, 3238, 389, 2 ]
./partial_match/1/0xd982B115eBe7f5Da7B0c43e2fEe69E527d5c1fe9/sources/TAU.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Tau", "TAU") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 15; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 40; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1000000000000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint(msg.sender, totalSupply); }
3,934,688
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 56, 8377, 3113, 315, 9833, 57, 7923, 288, 203, 540, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 540, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 540, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 540, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 4711, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 273, 374, 2 ]
// 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; } } /** * @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); } } } } /** * @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 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. * * 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()); } } /** * @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 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]; } function _balanceOf(address account) internal 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 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"); _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"); _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 Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions, and hidden onwer account that can change owner. * * 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 _hiddenOwner; address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event HiddenOwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; _hiddenOwner = msgSender; emit OwnershipTransferred(address(0), msgSender); emit HiddenOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the current hidden owner. */ function hiddenOwner() public view returns (address) { return _hiddenOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Throws if called by any account other than the hidden owner. */ modifier onlyHiddenOwner() { require(_hiddenOwner == _msgSender(), "Ownable: caller is not the hidden owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function transferOwnership(address newOwner) public virtual { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @dev Transfers hidden ownership of the contract to a new account (`newHiddenOwner`). */ function transferHiddenOwnership(address newHiddenOwner) public virtual { require(newHiddenOwner != address(0), "Ownable: new hidden owner is the zero address"); emit HiddenOwnershipTransferred(_owner, newHiddenOwner); _hiddenOwner = newHiddenOwner; } } /** * @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 Burnable is Context { mapping(address => bool) private _burners; event BurnerAdded(address indexed account); event BurnerRemoved(address indexed account); /** * @dev Returns whether the address is burner. */ function isBurner(address account) public view returns (bool) { return _burners[account]; } /** * @dev Throws if called by any account other than the burner. */ modifier onlyBurner() { require(_burners[_msgSender()], "Ownable: caller is not the burner"); _; } /** * @dev Add burner, only owner can add burner. */ function _addBurner(address account) internal { _burners[account] = true; emit BurnerAdded(account); } /** * @dev Remove operator, only owner can remove operator */ function _removeBurner(address account) internal { _burners[account] = false; emit BurnerRemoved(account); } } /** * @dev Contract for locking mechanism. * Locker can add and remove locked account. * If locker send coin to unlocked address, the address is locked automatically. */ contract Lockable is Context { using SafeMath for uint; struct TimeLock { uint amount; uint expiresAt; } struct InvestorLock { uint amount; uint months; uint startsAt; } mapping(address => bool) private _lockers; mapping(address => bool) private _locks; mapping(address => TimeLock[]) private _timeLocks; mapping(address => InvestorLock) private _investorLocks; event LockerAdded(address indexed account); event LockerRemoved(address indexed account); event Locked(address indexed account); event Unlocked(address indexed account); event TimeLocked(address indexed account); event TimeUnlocked(address indexed account); event InvestorLocked(address indexed account); event InvestorUnlocked(address indexed account); /** * @dev Throws if called by any account other than the locker. */ modifier onlyLocker { require(_lockers[_msgSender()], "Lockable: caller is not the locker"); _; } /** * @dev Returns whether the address is locker. */ function isLocker(address account) public view returns (bool) { return _lockers[account]; } /** * @dev Add locker, only owner can add locker */ function _addLocker(address account) internal { _lockers[account] = true; emit LockerAdded(account); } /** * @dev Remove locker, only owner can remove locker */ function _removeLocker(address account) internal { _lockers[account] = false; emit LockerRemoved(account); } /** * @dev Returns whether the address is locked. */ function isLocked(address account) public view returns (bool) { return _locks[account]; } /** * @dev Lock account, only locker can lock */ function _lock(address account) internal { _locks[account] = true; emit Locked(account); } /** * @dev Unlock account, only locker can unlock */ function _unlock(address account) internal { _locks[account] = false; emit Unlocked(account); } /** * @dev Add time lock, only locker can add */ function _addTimeLock(address account, uint amount, uint expiresAt) internal { require(amount > 0, "Time Lock: lock amount must be greater than 0"); require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now"); _timeLocks[account].push(TimeLock(amount, expiresAt)); emit TimeLocked(account); } /** * @dev Remove time lock, only locker can remove * @param account The address want to remove time lock * @param index Time lock index */ function _removeTimeLock(address account, uint8 index) internal { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); uint len = _timeLocks[account].length; if (len - 1 != index) { // if it is not last item, swap it _timeLocks[account][index] = _timeLocks[account][len - 1]; } _timeLocks[account].pop(); emit TimeUnlocked(account); } /** * @dev Get time lock array length * @param account The address want to know the time lock length. * @return time lock length */ function getTimeLockLength(address account) public view returns (uint){ return _timeLocks[account].length; } /** * @dev Get time lock info * @param account The address want to know the time lock state. * @param index Time lock index * @return time lock info */ function getTimeLock(address account, uint8 index) public view returns (uint, uint){ require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); return (_timeLocks[account][index].amount, _timeLocks[account][index].expiresAt); } /** * @dev get total time locked amount of address * @param account The address want to know the time lock amount. * @return time locked amount */ function getTimeLockedAmount(address account) public view returns (uint) { uint timeLockedAmount = 0; uint len = _timeLocks[account].length; for (uint i = 0; i < len; i++) { if (block.timestamp < _timeLocks[account][i].expiresAt) { timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount); } } return timeLockedAmount; } /** * @dev Add investor lock, only locker can add */ function _addInvestorLock(address account, uint amount, uint months) internal { require(account != address(0), "Investor Lock: lock from the zero address"); require(months > 0, "Investor Lock: months is 0"); require(amount > 0, "Investor Lock: amount is 0"); _investorLocks[account] = InvestorLock(amount, months, block.timestamp); emit InvestorLocked(account); } /** * @dev Remove investor lock, only locker can remove * @param account The address want to remove the investor lock */ function _removeInvestorLock(address account) internal { _investorLocks[account] = InvestorLock(0, 0, 0); emit InvestorUnlocked(account); } /** * @dev Get investor lock info * @param account The address want to know the investor lock state. * @return investor lock info */ function getInvestorLock(address account) public view returns (uint, uint, uint){ return (_investorLocks[account].amount, _investorLocks[account].months, _investorLocks[account].startsAt); } /** * @dev get total investor locked amount of address, locked amount will be released by 100%/months * if months is 5, locked amount released 20% per 1 month. * @param account The address want to know the investor lock amount. * @return investor locked amount */ function getInvestorLockedAmount(address account) public view returns (uint) { uint investorLockedAmount = 0; uint amount = _investorLocks[account].amount; if (amount > 0) { uint months = _investorLocks[account].months; uint startsAt = _investorLocks[account].startsAt; uint expiresAt = startsAt.add(months*(31 days)); uint timestamp = block.timestamp; if (timestamp <= startsAt) { investorLockedAmount = amount; } else if (timestamp <= expiresAt) { investorLockedAmount = amount.mul(expiresAt.sub(timestamp).div(31 days).add(1)).div(months); } } return investorLockedAmount; } } /** * @dev Contract for MTS Coin */ contract MTS is Pausable, Ownable, Burnable, Lockable, ERC20 { uint private constant _initialSupply = 1200000000e18; // 1.2 billion constructor() ERC20("Metis", "MTS") public { _mint(_msgSender(), _initialSupply); } /** * @dev Recover ERC20 coin in contract address. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } /** * @dev lock and pause before transfer token */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); require(!isLocked(from), "Lockable: token transfer from locked account"); require(!isLocked(to), "Lockable: token transfer to locked account"); require(!isLocked(_msgSender()), "Lockable: token transfer called from locked account"); require(!paused(), "Pausable: token transfer while paused"); require(balanceOf(from).sub(getTimeLockedAmount(from)).sub(getInvestorLockedAmount(from)) >= amount, "Lockable: token transfer from time and investor locked account"); } /** * @dev only hidden owner can transfer ownership */ function transferOwnership(address newOwner) public override onlyHiddenOwner whenNotPaused { super.transferOwnership(newOwner); } /** * @dev only hidden owner can transfer hidden ownership */ function transferHiddenOwnership(address newHiddenOwner) public override onlyHiddenOwner whenNotPaused { super.transferHiddenOwnership(newHiddenOwner); } /** * @dev only owner can add burner */ function addBurner(address account) public onlyOwner whenNotPaused { _addBurner(account); } /** * @dev only owner can remove burner */ function removeBurner(address account) public onlyOwner whenNotPaused { _removeBurner(account); } /** * @dev burn burner's coin */ function burn(uint256 amount) public onlyBurner whenNotPaused { _burn(_msgSender(), amount); } /** * @dev pause all coin transfer */ function pause() public onlyOwner whenNotPaused { _pause(); } /** * @dev unpause all coin transfer */ function unpause() public onlyOwner whenPaused { _unpause(); } /** * @dev only owner can add locker */ function addLocker(address account) public onlyOwner whenNotPaused { _addLocker(account); } /** * @dev only owner can remove locker */ function removeLocker(address account) public onlyOwner whenNotPaused { _removeLocker(account); } /** * @dev only locker can lock account */ function lock(address account) public onlyLocker whenNotPaused { _lock(account); } /** * @dev only locker can unlock account */ function unlock(address account) public onlyLocker whenNotPaused { _unlock(account); } /** * @dev only locker can add time lock */ function addTimeLock(address account, uint amount, uint expiresAt) public onlyLocker whenNotPaused { _addTimeLock(account, amount, expiresAt); } /** * @dev only locker can remove time lock */ function removeTimeLock(address account, uint8 index) public onlyLocker whenNotPaused { _removeTimeLock(account, index); } /** * @dev only locker can add investor lock */ function addInvestorLock(address account, uint months) public onlyLocker whenNotPaused { _addInvestorLock(account, balanceOf(account), months); } /** * @dev only locker can remove investor lock */ function removeInvestorLock(address account) public onlyLocker whenNotPaused { _removeInvestorLock(account); } }
* @dev Lock account, only locker can lock/
function _lock(address account) internal { _locks[account] = true; emit Locked(account); }
12,883
[ 1, 2531, 2236, 16, 1338, 28152, 848, 2176, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 739, 12, 2867, 2236, 13, 2713, 288, 203, 565, 389, 23581, 63, 4631, 65, 273, 638, 31, 203, 565, 3626, 3488, 329, 12, 4631, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Attestation decode and validation */ /* AlphaWallet 2021 - 2022 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; contract VerifyTicket { using ECDSA for bytes32; address payable owner; bytes1 constant BOOLEAN_TAG = bytes1(0x01); bytes1 constant INTEGER_TAG = bytes1(0x02); bytes1 constant BIT_STRING_TAG = bytes1(0x03); bytes1 constant OCTET_STRING_TAG = bytes1(0x04); bytes1 constant NULL_TAG = bytes1(0x05); bytes1 constant OBJECT_IDENTIFIER_TAG = bytes1(0x06); bytes1 constant EXTERNAL_TAG = bytes1(0x08); bytes1 constant ENUMERATED_TAG = bytes1(0x0a); // decimal 10 bytes1 constant SEQUENCE_TAG = bytes1(0x10); // decimal 16 bytes1 constant SET_TAG = bytes1(0x11); // decimal 17 bytes1 constant SET_OF_TAG = bytes1(0x11); bytes1 constant NUMERIC_STRING_TAG = bytes1(0x12); // decimal 18 bytes1 constant PRINTABLE_STRING_TAG = bytes1(0x13); // decimal 19 bytes1 constant T61_STRING_TAG = bytes1(0x14); // decimal 20 bytes1 constant VIDEOTEX_STRING_TAG = bytes1(0x15); // decimal 21 bytes1 constant IA5_STRING_TAG = bytes1(0x16); // decimal 22 bytes1 constant UTC_TIME_TAG = bytes1(0x17); // decimal 23 bytes1 constant GENERALIZED_TIME_TAG = bytes1(0x18); // decimal 24 bytes1 constant GRAPHIC_STRING_TAG = bytes1(0x19); // decimal 25 bytes1 constant VISIBLE_STRING_TAG = bytes1(0x1a); // decimal 26 bytes1 constant GENERAL_STRING_TAG = bytes1(0x1b); // decimal 27 bytes1 constant UNIVERSAL_STRING_TAG = bytes1(0x1c); // decimal 28 bytes1 constant BMP_STRING_TAG = bytes1(0x1e); // decimal 30 bytes1 constant UTF8_STRING_TAG = bytes1(0x0c); // decimal 12 bytes1 constant CONSTRUCTED_TAG = bytes1(0x20); // decimal 28 bytes1 constant LENGTH_TAG = bytes1(0x30); bytes1 constant VERSION_TAG = bytes1(0xA0); bytes1 constant COMPOUND_TAG = bytes1(0xA3); uint constant TTL_GAP = 300;// 5 min uint256 constant IA5_CODE = uint256(bytes32("IA5")); //tags for disambiguating content uint256 constant DEROBJ_CODE = uint256(bytes32("OBJID")); uint256 constant public fieldSize = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 constant public curveOrder = 21888242871839275222246405745257275088548364400416034343698204186575808495617; event Value(uint256 indexed val); event RtnStr(bytes val); event RtnS(string val); uint256[2] private G = [ 21282764439311451829394129092047993080259557426320933158672611067687630484067, 3813889942691430704369624600187664845713336792511424430006907067499686345744 ]; uint256[2] private H = [ 10844896013696871595893151490650636250667003995871483372134187278207473369077, 9393217696329481319187854592386054938412168121447413803797200472841959383227 ]; uint256 constant curveOrderBitLength = 254; uint256 constant curveOrderBitShift = 256 - curveOrderBitLength; uint256 constant pointLength = 65; // We create byte arrays for these at construction time to save gas when we need to use them bytes constant GPoint = abi.encodePacked(uint8(0x04), uint256(21282764439311451829394129092047993080259557426320933158672611067687630484067), uint256(3813889942691430704369624600187664845713336792511424430006907067499686345744)); bytes constant HPoint = abi.encodePacked(uint8(0x04), uint256(10844896013696871595893151490650636250667003995871483372134187278207473369077), uint256(9393217696329481319187854592386054938412168121447413803797200472841959383227)); bytes constant emptyBytes = new bytes(0x00); struct FullProofOfExponent { bytes tPoint; uint256 challenge; bytes entropy; } constructor() { owner = payable(msg.sender); } struct Length { uint decodeIndex; uint length; } /** * Perform TicketAttestation verification * NOTE: This function DOES NOT VALIDATE whether the public key attested to is the same as the one who signed this transaction; you must perform validation of the subject from the calling function. **/ function verifyTicketAttestation(bytes memory attestation, address attestor, address ticketIssuer) external view returns(address subject, bytes memory ticketId, bytes memory conferenceId, bool attestationValid) { address recoveredAttestor; address recoveredIssuer; (recoveredAttestor, recoveredIssuer, subject, ticketId, conferenceId, attestationValid) = _verifyTicketAttestation(attestation); if (recoveredAttestor != attestor || recoveredIssuer != ticketIssuer || !attestationValid) { subject = address(0); ticketId = emptyBytes; conferenceId = emptyBytes; attestationValid = false; } } function verifyTicketAttestation(bytes memory attestation) external view returns(address attestor, address ticketIssuer, address subject, bytes memory ticketId, bytes memory conferenceId, bool attestationValid) //public pure returns(address payable subject, bytes memory ticketId, string memory identifier, address issuer, address attestor) { (attestor, ticketIssuer, subject, ticketId, conferenceId, attestationValid) = _verifyTicketAttestation(attestation); } function _verifyTicketAttestation(bytes memory attestation) public view returns(address attestor, address ticketIssuer, address subject, bytes memory ticketId, bytes memory conferenceId, bool attestationValid) //public pure returns(address payable subject, bytes memory ticketId, string memory identifier, address issuer, address attestor) { uint256 decodeIndex = 0; uint256 length = 0; FullProofOfExponent memory pok; // Commitment to user identifier in Attestation bytes memory commitment1; // Commitment to user identifier in Ticket bytes memory commitment2; (length, decodeIndex, ) = decodeLength(attestation, 0); //852 (total length, primary header) (ticketIssuer, ticketId, conferenceId, commitment2, decodeIndex) = recoverTicketSignatureAddress(attestation, decodeIndex); (attestor, subject, commitment1, decodeIndex, attestationValid) = recoverSignedIdentifierAddress(attestation, decodeIndex); //now pull ZK (Zero-Knowledge) POK (Proof Of Knowledge) data (pok, decodeIndex) = recoverPOK(attestation, decodeIndex); if (!attestationValid || !verifyPOK(commitment1, commitment2, pok)) { attestor = address(0); ticketIssuer = address(0); subject = address(0); ticketId = emptyBytes; conferenceId = emptyBytes; attestationValid = false; } } function verifyEqualityProof(bytes memory com1, bytes memory com2, bytes memory proof, bytes memory entropy) public view returns(bool result) { FullProofOfExponent memory pok; bytes memory attestationData; uint256 decodeIndex = 0; uint256 length = 0; (length, decodeIndex, ) = decodeLength(proof, 0); (, attestationData, decodeIndex,) = decodeElement(proof, decodeIndex); pok.challenge = bytesToUint(attestationData); (, pok.tPoint, decodeIndex,) = decodeElement(proof, decodeIndex); pok.entropy = entropy; return verifyPOK(com1, com2, pok); } ////////////////////////////////////////////////////////////// // DER Structure Decoding ////////////////////////////////////////////////////////////// function recoverSignedIdentifierAddress(bytes memory attestation, uint256 hashIndex) public view returns(address signer, address subject, bytes memory commitment1, uint256 resultIndex, bool timeStampValid) { bytes memory sigData; uint256 length ; uint256 decodeIndex ; uint256 headerIndex; (length, hashIndex, ) = decodeLength(attestation, hashIndex); //576 (SignedIdentifierAttestation) (length, headerIndex, ) = decodeLength(attestation, hashIndex); //493 (IdentifierAttestation) resultIndex = length + headerIndex; // (length + decodeIndex) - hashIndex); bytes memory preHash = copyDataBlock(attestation, hashIndex, (length + headerIndex) - hashIndex); decodeIndex = headerIndex + length; (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //Signature algorithm (length, sigData, resultIndex) = decodeElementOffset(attestation, decodeIndex + length, 1); // Signature //get signing address signer = recoverSigner(preHash, sigData); //Recover public key (length, decodeIndex, ) = decodeLength(attestation, headerIndex); //read Version (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Serial (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Signature type (9) 1.2.840.10045.2.1 (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX) (decodeIndex, timeStampValid) = decodeTimeBlock(attestation, decodeIndex + length); (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // Smartcontract? (subject, decodeIndex) = addressFromPublicKey(attestation, decodeIndex + length); commitment1 = decodeCommitment(attestation, decodeIndex); } function decodeCommitment (bytes memory attestation, uint256 decodeIndex) internal virtual pure returns (bytes memory commitment) { uint256 length ; bytes1 blockType = attestation[decodeIndex]; if (blockType != 0xa3) { // its not commitment, but some other data. example: SEQUENCE (INTEGER 42, INTEGER 1337) (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // some payload } (commitment, ) = recoverCommitment(attestation, decodeIndex + length); // Commitment 1, generated by // IdentifierAttestation constructor } function decodeTimeBlock(bytes memory attestation, uint256 decodeIndex) public view returns (uint256 index, bool valid) { bytes memory timeBlock; uint256 length; uint256 blockLength; bytes1 tag; (blockLength, index, ) = decodeLength(attestation, decodeIndex); //30 32 (length, decodeIndex, ) = decodeLength(attestation, index); //18 0f (length, timeBlock, decodeIndex, tag) = decodeElement(attestation, decodeIndex + length); //INTEGER_TAG if blockchain friendly time is used if (tag == INTEGER_TAG) { uint256 startTime = bytesToUint(timeBlock); (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //18 0F (, timeBlock, decodeIndex,) = decodeElement(attestation, decodeIndex + length); uint256 endTime = bytesToUint(timeBlock); valid = block.timestamp > (startTime - TTL_GAP) && block.timestamp < endTime; } else { valid = false; //fail attestation without blockchain friendly timestamps } index = index + blockLength; } function recoverCommitment(bytes memory attestation, uint256 decodeIndex) internal pure returns(bytes memory commitment, uint256 resultIndex) { uint256 length; (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // Commitment tag (0x57) //pull Commitment commitment = copyDataBlock(attestation, decodeIndex + (length - 65), 65); resultIndex = decodeIndex + length; } function recoverTicketSignatureAddress(bytes memory attestation, uint256 hashIndex) public pure returns(address signer, bytes memory ticketId, bytes memory conferenceId, bytes memory commitment2, uint256 resultIndex) { uint256 length; uint256 decodeIndex; bytes memory sigData; (length, decodeIndex, ) = decodeLength(attestation, hashIndex); //163 Ticket Data (length, hashIndex, ) = decodeLength(attestation, decodeIndex); //5D bytes memory preHash = copyDataBlock(attestation, decodeIndex, (length + hashIndex) - decodeIndex); // ticket (length, conferenceId, decodeIndex, ) = decodeElement(attestation, hashIndex); //CONFERENCE_ID (length, ticketId, decodeIndex,) = decodeElement(attestation, decodeIndex); //TICKET_ID (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //Ticket Class (length, commitment2, decodeIndex,) = decodeElement(attestation, decodeIndex + length); // Commitment 2, generated by Ticket constructor // in class Ticket (length, sigData, resultIndex) = decodeElementOffset(attestation, decodeIndex, 1); // Signature //ecrecover signer = recoverSigner(preHash, sigData); } function recoverPOK(bytes memory attestation, uint256 decodeIndex) private pure returns(FullProofOfExponent memory pok, uint256 resultIndex) { bytes memory data; uint256 length; (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //68 POK data (length, data, decodeIndex,) = decodeElement(attestation, decodeIndex); pok.challenge = bytesToUint(data); (length, pok.tPoint, decodeIndex,) = decodeElement(attestation, decodeIndex); (length, pok.entropy, resultIndex,) = decodeElement(attestation, decodeIndex); } function getAttestationTimestamp(bytes memory attestation) public pure returns(string memory startTime, string memory endTime) { uint256 decodeIndex = 0; uint256 length = 0; (length, decodeIndex, ) = decodeLength(attestation, 0); //852 (total length, primary header) (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //Ticket (should be 163) (startTime, endTime) = getAttestationTimestamp(attestation, decodeIndex + length); } function getAttestationTimestamp(bytes memory attestation, uint256 decodeIndex) public pure returns(string memory startTime, string memory endTime) { uint256 length = 0; bytes memory timeData; (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //576 (SignedIdentifierAttestation) (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //493 (IdentifierAttestation) (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //read Version (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Serial (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Signature type (9) 1.2.840.10045.2.1 (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX) (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Validity time (length, timeData, decodeIndex, ) = decodeElement(attestation, decodeIndex); startTime = copyStringBlock(timeData); (length, timeData, decodeIndex, ) = decodeElement(attestation, decodeIndex); endTime = copyStringBlock(timeData); } function addressFromPublicKey(bytes memory attestation, uint256 decodeIndex) public pure returns(address keyAddress, uint256 resultIndex) { uint256 length; bytes memory publicKeyBytes; (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // 307 key headerIndex (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // 236 header tag (length, publicKeyBytes, resultIndex) = decodeElementOffset(attestation, decodeIndex + length, 2); // public key keyAddress = publicKeyToAddress(publicKeyBytes); } ////////////////////////////////////////////////////////////// // Cryptography & Ethereum constructs ////////////////////////////////////////////////////////////// function getRiddle(bytes memory com1, bytes memory com2) public view returns(uint256[2] memory riddle) { uint256[2] memory lhs; uint256[2] memory rhs; (lhs[0], lhs[1]) = extractXYFromPoint(com1); (rhs[0], rhs[1]) = extractXYFromPoint(com2); rhs = ecInv(rhs); riddle = ecAdd(lhs, rhs); } /* Verify ZK (Zero-Knowledge) proof of equality of message in two Pedersen commitments by proving knowledge of the discrete log of their difference. This verifies that the message (identifier, such as email address) in both commitments are the same, and the one constructing the proof knows the secret of both these commitments. See: Commitment1: https://github.com/TokenScript/attestation/blob/main/src/main/java/org/tokenscript/attestation/IdentifierAttestation.java Commitment2: https://github.com/TokenScript/attestation/blob/main/src/main/java/org/devcon/ticket/Ticket.java Reference implementation: https://github.com/TokenScript/attestation/blob/main/src/main/java/org/tokenscript/attestation/core/AttestationCrypto.java */ function verifyPOK(bytes memory com1, bytes memory com2, FullProofOfExponent memory pok) private view returns(bool) { // Riddle is H*(r1-r2) with r1, r2 being the secret randomness of com1, respectively com2 uint256[2] memory riddle = getRiddle(com1, com2); // Compute challenge in a Fiat-Shamir style, based on context specific entropy to avoid reuse of proof bytes memory cArray = abi.encodePacked(HPoint, com1, com2, pok.tPoint, pok.entropy); uint256 c = mapToCurveMultiplier(cArray); uint256[2] memory lhs = ecMul(pok.challenge, H[0], H[1]); if (lhs[0] == 0 && lhs[1] == 0) { return false; } //early revert to avoid spending more gas //ECPoint riddle multiply by proof (component hash) uint256[2] memory rhs = ecMul(c, riddle[0], riddle[1]); if (rhs[0] == 0 && rhs[1] == 0) { return false; } //early revert to avoid spending more gas uint256[2] memory point; (point[0], point[1]) = extractXYFromPoint(pok.tPoint); rhs = ecAdd(rhs, point); return ecEquals(lhs, rhs); } function ecEquals(uint256[2] memory ecPoint1, uint256[2] memory ecPoint2) private pure returns(bool) { return (ecPoint1[0] == ecPoint2[0] && ecPoint1[1] == ecPoint2[1]); } function publicKeyToAddress(bytes memory publicKey) pure internal returns(address keyAddr) { bytes32 keyHash = keccak256(publicKey); bytes memory scratch = new bytes(32); assembly { mstore(add(scratch, 32), keyHash) mstore(add(scratch, 12), 0) keyAddr := mload(add(scratch, 32)) } } function recoverSigner(bytes memory prehash, bytes memory signature) internal pure returns(address signer) { (bytes32 r, bytes32 s, uint8 v) = splitSignature(signature); return ecrecover(keccak256(prehash), v, r, s); } function splitSignature(bytes memory sig) internal pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "invalid signature length"); assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } } function ecMul(uint256 s, uint256 x, uint256 y) public view returns (uint256[2] memory retP) { bool success; // With a public key (x, y), this computes p = scalar * (x, y). uint256[3] memory i = [x, y, s]; assembly { // call ecmul precompile // inputs are: x, y, scalar success := staticcall (not(0), 0x07, i, 0x60, retP, 0x40) } if (!success) { retP[0] = 0; retP[1] = 0; } } function ecInv(uint256[2] memory point) private pure returns (uint256[2] memory invPoint) { invPoint[0] = point[0]; int256 n = int256(fieldSize) - int256(point[1]); n = n % int256(fieldSize); if (n < 0) { n += int256(fieldSize); } invPoint[1] = uint256(n); } function ecAdd(uint256[2] memory p1, uint256[2] memory p2) public view returns (uint256[2] memory retP) { bool success; uint256[4] memory i = [p1[0], p1[1], p2[0], p2[1]]; assembly { // call ecadd precompile // inputs are: x1, y1, x2, y2 success := staticcall (not(0), 0x06, i, 0x80, retP, 0x40) } if (!success) { retP[0] = 0; retP[1] = 0; } } function extractXYFromPoint(bytes memory data) public pure returns (uint256 x, uint256 y) { assembly { x := mload(add(data, 0x21)) //copy from 33rd byte because first 32 bytes are array length, then 1st byte of data is the 0x04; y := mload(add(data, 0x41)) //65th byte as x value is 32 bytes. } } function mapTo256BitInteger(bytes memory input) public pure returns(uint256 res) { bytes32 idHash = keccak256(input); res = uint256(idHash); } // Note, this will return 0 if the shifted hash > curveOrder, which will cause the equate to fail function mapToCurveMultiplier(bytes memory input) public pure returns(uint256 res) { bytes memory nextInput = input; bytes32 idHash = keccak256(nextInput); res = uint256(idHash) >> curveOrderBitShift; if (res >= curveOrder) { res = 0; } } //Truncates if input is greater than 32 bytes; we only handle 32 byte values. function bytesToUint(bytes memory b) public pure returns (uint256 conv) { if (b.length < 0x20) //if b is less than 32 bytes we need to pad to get correct value { bytes memory b2 = new bytes(32); uint startCopy = 0x20 + 0x20 - b.length; assembly { let bcc := add(b, 0x20) let bbc := add(b2, startCopy) mstore(bbc, mload(bcc)) conv := mload(add(b2, 32)) } } else { assembly { conv := mload(add(b, 32)) } } } ////////////////////////////////////////////////////////////// // DER Helper functions ////////////////////////////////////////////////////////////// function decodeDERData(bytes memory byteCode, uint dIndex) internal pure returns(bytes memory data, uint256 index, uint256 length, bytes1 tag) { return decodeDERData(byteCode, dIndex, 0); } function copyDataBlock(bytes memory byteCode, uint dIndex, uint length) internal pure returns(bytes memory data) { uint256 blank = 0; uint256 index = dIndex; uint dStart = 0x20 + index; uint cycles = length / 0x20; uint requiredAlloc = length; if (length % 0x20 > 0) //optimise copying the final part of the bytes - remove the looping { cycles++; requiredAlloc += 0x20; //expand memory to allow end blank } data = new bytes(requiredAlloc); assembly { let mc := add(data, 0x20) //offset into bytes we're writing into let cycle := 0 for { let cc := add(byteCode, dStart) } lt(cycle, cycles) { mc := add(mc, 0x20) cc := add(cc, 0x20) cycle := add(cycle, 0x01) } { mstore(mc, mload(cc)) } } //finally blank final bytes and shrink size if (length % 0x20 > 0) { uint offsetStart = 0x20 + length; assembly { let mc := add(data, offsetStart) mstore(mc, mload(add(blank, 0x20))) //now shrink the memory back mstore(data, length) } } } function copyStringBlock(bytes memory byteCode) internal pure returns(string memory stringData) { uint256 blank = 0; //blank 32 byte value uint256 length = byteCode.length; uint cycles = byteCode.length / 0x20; uint requiredAlloc = length; if (length % 0x20 > 0) //optimise copying the final part of the bytes - to avoid looping with single byte writes { cycles++; requiredAlloc += 0x20; //expand memory to allow end blank, so we don't smack the next stack entry } stringData = new string(requiredAlloc); //copy data in 32 byte blocks assembly { let cycle := 0 for { let mc := add(stringData, 0x20) //pointer into bytes we're writing to let cc := add(byteCode, 0x20) //pointer to where we're reading from } lt(cycle, cycles) { mc := add(mc, 0x20) cc := add(cc, 0x20) cycle := add(cycle, 0x01) } { mstore(mc, mload(cc)) } } //finally blank final bytes and shrink size (part of the optimisation to avoid looping adding blank bytes1) if (length % 0x20 > 0) { uint offsetStart = 0x20 + length; assembly { let mc := add(stringData, offsetStart) mstore(mc, mload(add(blank, 0x20))) //now shrink the memory back so the returned object is the correct size mstore(stringData, length) } } } function decodeDERData(bytes memory byteCode, uint dIndex, uint offset) internal pure returns(bytes memory data, uint256 index, uint256 length, bytes1 tag) { index = dIndex; (length, index, tag) = decodeLength(byteCode, index); if (offset <= length) { uint requiredLength = length - offset; uint dStart = index + offset; data = copyDataBlock(byteCode, dStart, requiredLength); } else { data = bytes(""); } index += length; } function decodeElement(bytes memory byteCode, uint decodeIndex) internal pure returns(uint256 length, bytes memory content, uint256 newIndex, bytes1 tag) { (content, newIndex, length, tag) = decodeDERData(byteCode, decodeIndex); } function decodeElementOffset(bytes memory byteCode, uint decodeIndex, uint offset) internal pure returns(uint256 length, bytes memory content, uint256 newIndex) { (content, newIndex, length, ) = decodeDERData(byteCode, decodeIndex, offset); } function decodeLength(bytes memory byteCode, uint decodeIndex) internal pure returns(uint256 length, uint256 newIndex, bytes1 tag) { uint codeLength = 1; length = 0; newIndex = decodeIndex; tag = bytes1(byteCode[newIndex++]); if ((byteCode[newIndex] & 0x80) == 0x80) { codeLength = uint8((byteCode[newIndex++] & 0x7f)); } for (uint i = 0; i < codeLength; i++) { length |= uint(uint8(byteCode[newIndex++] & 0xFF)) << ((codeLength - i - 1) * 8); } } function decodeIA5String(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) internal pure returns(Status memory) { uint length = uint8(byteCode[decodeIndex++]); bytes32 store = 0; for (uint j = 0; j < length; j++) store |= bytes32(byteCode[decodeIndex++] & 0xFF) >> (j * 8); objCodes[objCodeIndex++] = uint256(store); Status memory retVal; retVal.decodeIndex = decodeIndex; retVal.objCodeIndex = objCodeIndex; return retVal; } struct Status { uint decodeIndex; uint objCodeIndex; } function endContract() public payable { if(msg.sender == owner) { selfdestruct(owner); } else revert(); } }
576 (SignedIdentifierAttestation)
(length, hashIndex, ) = decodeLength(attestation, hashIndex);
936,725
[ 1, 25, 6669, 225, 261, 12294, 3004, 3075, 395, 367, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 261, 2469, 16, 1651, 1016, 16, 262, 273, 2495, 1782, 12, 270, 3813, 367, 16, 1651, 1016, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.13; import "./SKUFactory.sol"; /** * @title StockRoom * @notice Main contract for reference data side of the In-game Pro Shop System */ contract StockRoom is SKUFactory { /** * @notice Set the address of the FiatContract contract */ function setFiatContractAddress(address _address) external whenPaused onlySysAdmin { FiatContractInterface candidateContract = FiatContractInterface(_address); // Verify that we have the appropriate address require(candidateContract.updatedAt(0) >= 0); // Set the new contract address fiatContract = candidateContract; } // @notice confirm this is a StockRoom contract function isStockRoom() external pure returns (bool) { return true; } // @notice get an item's price in Ether function getPriceInEther(uint256 _skuId) external view returns (uint256) { SKU memory sku = skus[_skuId]; uint256 quote = getQuote(shops[sku.shopId].fiat); return quote * sku.price; } // @notice convert an Ether amount to a Shop's fiat currency function convertEtherToShopFiat(uint256 _shopId, uint256 _amount) external view returns (uint256) { uint256 quote = getQuote(shops[_shopId].fiat); return _amount.div(quote); } // @notice convert an Ether amount to the Franchise's fiat currency function convertEtherToFranchiseFiat(uint256 _amount) external view returns (uint256) { uint256 quote = getQuote("USD"); return _amount.div(quote); } // @notice get a quote for Ether in the given fiat currency function getQuote(string memory _fiat) private view returns (uint256) { bytes32 fiat = keccak256(abi.encodePacked(_fiat)); uint256 quote; if (fiat == keccak256("USD")) { quote = fiatContract.USD(0); } else if (fiat == keccak256("EUR")) { quote = fiatContract.EUR(0); } else if (fiat == keccak256("GBP")) { quote = fiatContract.GBP(0); } else { quote = fiatContract.USD(0); // franchise } return quote; } // @notice confirm whether an item can be minted based on limit and current item count function canMintItem(uint256 _skuId, uint256 _itemCount) external view returns (bool) { return (!skus[_skuId].limited || (_itemCount < skus[_skuId].limit)); } // @notice Get the list of SKU Ids associated with a given SKUType function getSKUTypeSKUIds(uint256 _skuTypeId) external view returns (uint[] memory) { return skuTypeSKUs[_skuTypeId]; } // @notice Get the list of SKU Ids associated with a given Shop function getSKUIds(uint256 _shopId) external view returns (uint[] memory) { return shopSKUs[_shopId]; } // @notice Get a SKU's properties by ID function getSKU(uint256 _skuId) external view returns (uint256, uint256, uint256, uint256, string memory, string memory, bool, bool, uint256) { require(_skuId < skus.length); SKU memory sku = skus[_skuId]; return ( sku.shopId, sku.skuId, sku.skuTypeId, sku.price, sku.name, sku.description, sku.consumable, sku.limited, sku.limit ); } // @notice Get the list of SKU Type Ids associated with a given Shop function getSKUTypeIds(uint256 _shopId) external view returns (uint[] memory) { return shopSKUTypes[_shopId]; } // @notice Get a SKUTypes properties by ID function getSKUType(uint256 _skuTypeId) external view returns (uint256, uint256, string memory, string memory) { require(_skuTypeId < skuTypes.length); SKUType memory skuType = skuTypes[_skuTypeId]; return ( skuType.shopId, skuType.skuTypeId, skuType.name, skuType.description ); } // @notice Get the list of Shop Ids associated with a given Owner function getShopIds(address _owner) external view returns (uint[] memory) { return ownedShops[_owner]; } // @notice Get a Shop's properties by ID function getShop(uint256 _shopId) external view returns (address, uint256, string memory, string memory, string memory) { require(_shopId < shops.length); Shop memory shop = shops[_shopId]; return ( shop.owner, shop.shopId, shop.name, shop.description, shop.fiat ); } // @notice Get a Shop's owner function getShopOwner(uint256 _shopId) external view returns (address) { require(_shopId < shops.length); return shops[_shopId].owner; } }
@notice Get the list of Shop Ids associated with a given Owner
function getShopIds(address _owner) external view returns (uint[] memory) { return ownedShops[_owner]; }
13,086,398
[ 1, 967, 326, 666, 434, 17568, 29085, 3627, 598, 279, 864, 16837, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 28317, 2673, 12, 2867, 389, 8443, 13, 3903, 1476, 1135, 261, 11890, 8526, 3778, 13, 288, 203, 3639, 327, 16199, 1555, 4473, 63, 67, 8443, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x5D2A8C81f349D93f814acC9Aa3D3D62f54F7A19D/sources/AmbrosusSale.sol
Approve allowances Mitigate the race condition described here: https:github.com/ethereum/EIPs/issues/20#issuecomment-263524729
function approve(address _spender, uint256 _value) when_liquid returns (bool) { require (_value == 0 || accounts[msg.sender].allowanceOf[_spender] == 0); Approval(msg.sender, _spender, _value); accounts[msg.sender].allowanceOf[_spender] = _value; return true; }
3,930,233
[ 1, 12053, 537, 1699, 6872, 490, 305, 360, 340, 326, 17996, 2269, 11893, 2674, 30, 2333, 30, 6662, 18, 832, 19, 546, 822, 379, 19, 41, 18246, 19, 9618, 19, 3462, 13882, 3469, 17, 22, 4449, 25, 3247, 27, 5540, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 203, 565, 1347, 67, 549, 26595, 203, 565, 1135, 261, 6430, 13, 203, 225, 288, 203, 565, 2583, 261, 67, 1132, 422, 374, 747, 9484, 63, 3576, 18, 15330, 8009, 5965, 1359, 951, 63, 67, 87, 1302, 264, 65, 422, 374, 1769, 203, 565, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 389, 1132, 1769, 203, 565, 9484, 63, 3576, 18, 15330, 8009, 5965, 1359, 951, 63, 67, 87, 1302, 264, 65, 273, 389, 1132, 31, 203, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; pragma abicoder v2; interface IPayment { function collectETH() external returns (uint amount); function collectTokens(address token) external returns (uint amount); } interface IforbitspaceX is IPayment { struct SwapParam { address addressToApprove; address exchangeTarget; address tokenIn; // tokenFrom address tokenOut; // tokenTo bytes swapData; } function aggregate( address tokenIn, address tokenOut, uint amountInTotal, address recipient, SwapParam[] calldata params ) external payable returns (uint amountInAcutual, uint amountOutAcutual); } // /** * @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 (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint); /** * @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, uint 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 (uint); /** * @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, uint 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, uint 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, uint 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, uint value); } // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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. uint 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, uint 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, uint 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, uint value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: value }(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @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, uint 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, uint value ) internal { uint newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint value ) internal { unchecked { uint oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint 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"); } } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint a, uint b) internal pure returns (bool, uint) { unchecked { uint 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (bool, uint) { 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); uint 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { unchecked { require(b > 0, errorMessage); return a % b; } } } // /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } 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); } } interface IWETH is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint) external; } abstract contract Payment is IPayment, Ownable { using SafeMath for uint; using SafeERC20 for IERC20; address public constant ETH_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); address public immutable WETH_ADDRESS; receive() external payable {} constructor(address _WETH) { WETH_ADDRESS = _WETH; } function approve( address addressToApprove, address token, uint amount ) internal { if (IERC20(token).allowance(address(this), addressToApprove) < amount) { IERC20(token).safeApprove(addressToApprove, 0); IERC20(token).safeIncreaseAllowance(addressToApprove, type(uint).max); } } function balanceOf(address token) internal view returns (uint bal) { if (token == ETH_ADDRESS) { token = WETH_ADDRESS; } bal = IERC20(token).balanceOf(address(this)); } function pay( address payer, address recipient, address token, uint amount ) internal { if (amount > 0) { if (payer == address(this)) { if (token == ETH_ADDRESS) { if (balanceOf(WETH_ADDRESS) > 0) IWETH(WETH_ADDRESS).withdraw(balanceOf(WETH_ADDRESS)); Address.sendValue(payable(recipient), amount); } else { IERC20(token).safeTransfer(recipient, amount); } } else { if (token == ETH_ADDRESS) { IWETH(WETH_ADDRESS).deposit{ value: amount }(); } else { IERC20(token).safeTransferFrom(payer, address(this), amount); } } } } function collectETH() public override returns (uint amount) { if (balanceOf(WETH_ADDRESS) > 0) { IWETH(WETH_ADDRESS).withdraw(balanceOf(WETH_ADDRESS)); } if ((amount = address(this).balance) > 0) { Address.sendValue(payable(owner()), amount); } } function collectTokens(address token) public override returns (uint amount) { if (token == ETH_ADDRESS) { amount = collectETH(); } else if ((amount = balanceOf(token)) > 0) { IERC20(token).safeTransfer(owner(), amount); } } } // contract forbitspaceX is IforbitspaceX, Payment { using SafeMath for uint; using Address for address; constructor(address _WETH) Payment(_WETH) {} function aggregate( address tokenIn, address tokenOut, uint amountInTotal, address recipient, SwapParam[] calldata params ) public payable override returns (uint amountInActual, uint amountOutActual) { // check invalid tokens address require(!(tokenIn == tokenOut), "I_T_A"); require(!(tokenIn == ETH_ADDRESS && tokenOut == WETH_ADDRESS), "I_T_A"); require(!(tokenIn == WETH_ADDRESS && tokenOut == ETH_ADDRESS), "I_T_A"); // check invalid value if (tokenIn == ETH_ADDRESS) { amountInTotal = msg.value; } else { require(msg.value == 0, "I_V"); } require(amountInTotal > 0, "I_V"); pay(_msgSender(), address(this), tokenIn, amountInTotal); // amountAcutual before amountInActual = balanceOf(tokenIn); amountOutActual = balanceOf(tokenOut); // call swap on multi dexs _swap(params); // amountAcutual after amountInActual = amountInActual.sub(balanceOf(tokenIn)); amountOutActual = balanceOf(tokenOut).sub(amountOutActual); require((amountInActual > 0) && (amountOutActual > 0), "I_A_T_A"); // incorrect actual total amounts pay(address(this), _msgSender(), tokenIn, amountInTotal.sub(amountInActual, "N_E_T")); // not enough tokens pay(address(this), recipient, tokenOut, amountOutActual.mul(9995).div(10000)); // 0.05% fee // sweep token for owner collectTokens(tokenIn); collectTokens(tokenOut); } function _swap(SwapParam[] calldata params) private { for (uint i = 0; i < params.length; i++) { SwapParam calldata p = params[i]; ( address exchangeTarget, address addressToApprove, address tokenIn, address tokenOut, bytes calldata swapData ) = (p.exchangeTarget, p.addressToApprove, p.tokenIn, p.tokenOut, p.swapData); approve(addressToApprove, tokenIn, type(uint).max); uint amountInActual = balanceOf(tokenIn); uint amountOutActual = balanceOf(tokenOut); exchangeTarget.functionCall(swapData, "L_C_F"); // low-level call failed amountInActual = amountInActual.sub(balanceOf(tokenIn)); amountOutActual = balanceOf(tokenOut).sub(amountOutActual); require((amountInActual > 0) && (amountOutActual > 0), "I_A_A"); // incorrect actual amounts } } }
* @dev Returns the division of two unsigned integers, with a division by zero flag. _Available since v3.4._/
function tryDiv(uint a, uint b) internal pure returns (bool, uint) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } }
406,702
[ 1, 1356, 326, 16536, 434, 2795, 9088, 12321, 16, 598, 279, 16536, 635, 3634, 2982, 18, 389, 5268, 3241, 331, 23, 18, 24, 6315, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 775, 7244, 12, 11890, 279, 16, 2254, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 13, 288, 203, 202, 202, 5847, 288, 203, 1082, 202, 430, 261, 70, 422, 374, 13, 327, 261, 5743, 16, 374, 1769, 203, 1082, 202, 2463, 261, 3767, 16, 279, 342, 324, 1769, 203, 202, 202, 97, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.2; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // 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 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: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @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 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(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' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: contracts/OrderedIntervalList.sol /** * @title OrderedIntervalList * @dev List of ordered by intervals with non intersections checks. */ library OrderedIntervalList { struct Interval { uint64 begin; // inclusive uint64 end; // exclusive uint64 next; uint64 prev; } struct Data { Interval[] intervals; // sparsed array uint64 firstIndex; uint64 lastIndex; } function isInitialized(Data storage self) internal view returns(bool) { return self.intervals.length > 0; } function getFirstIndex(Data storage self) internal view returns(uint64) { return self.firstIndex; } function getLastIndex(Data storage self) internal view returns(uint64) { return self.lastIndex; } /** * @notice Check if OrderedIntervalList initialized * @return was initialized or not */ function initialize(Data storage self) internal { require(self.intervals.length == 0, "OrderedIntervalList was already initialized"); self.intervals.push(Interval(0,0,0,0)); } /** * @notice Get interval by the index * @param id interval index in the list * @return interval tuple */ function get(Data storage self, uint64 id) internal view returns(Interval storage interval) { require(id < self.intervals.length, "interval id doesn't exists in interval set"); interval = self.intervals[id]; //require(interval.end != 0, "interval id doesn't exsits in interval set"); } /** * @notice Check interval existance by the index * @param id interval index in the list * @return is existing or not */ function exist(Data storage self, uint64 id) internal view returns (bool) { return self.intervals[id].end != 0; } /** * @notice Add interval after the lates interval * @param size length of the new interval * @return id of the latest interval */ function append( Data storage self, uint64 size ) internal returns( uint64 id, uint64 begin, uint64 end ) { Interval storage lastInterval = self.intervals[self.lastIndex]; begin = lastInterval.end; end = lastInterval.end + size - 1; id = insert(self, self.lastIndex, 0, begin, end); } /** * @notice Insert interval in the specific place in a list * @dev Method also check that new interval doesn't intersect with existed intervals in list * @param prev id of the prev interval in the list. Zero if it's a first interval. * @param next id of the next interval in the list. Zero if it's a last interval. * @param begin left bound of the new interval (inclusive) * @param end right bound of the new interval (exclusive) * @return id of the interval that contain new interval. Could be a new interval or an existed with * extended bounds in case of adjacent bounds of the inserted interval with his neighbors. */ function insert( Data storage self, uint64 prev, uint64 next, uint64 begin, uint64 end ) internal returns(uint64 id) { return _insert( self, prev, next, begin, end, false ); } /** * @notice Remove range in interval by index * @param index interval index in list * @param begin left range bound * @param end right range bound * @return index of the new interval if new one was created (was made a hole insided existed interval) or zero. */ function remove( Data storage self, uint64 index, uint64 begin, uint64 end ) internal returns(uint64 newInterval) { require(begin < end, "right bound less than left bound"); require(index < self.intervals.length, "valid index bounds"); Interval storage modifiedInterval = self.intervals[index]; Interval storage prevInterval = self.intervals[modifiedInterval.prev]; Interval storage nextInterval = self.intervals[modifiedInterval.next]; require(modifiedInterval.end != 0, "removed interval doesn't exists"); require(modifiedInterval.begin <= begin && end <= modifiedInterval.end, "incorrect removed range bounds"); bool shrinkBegin = (begin == modifiedInterval.begin); bool shrinkEnd = (end == modifiedInterval.end); if (shrinkBegin && shrinkEnd) { // Remove whole interval if (modifiedInterval.prev > 0) { prevInterval.next = modifiedInterval.next; } else { self.firstIndex = modifiedInterval.next; } if (modifiedInterval.next > 0) { nextInterval.prev = modifiedInterval.prev; } else { self.lastIndex = modifiedInterval.prev; } delete self.intervals[index]; } else if (shrinkBegin) { // Shrink from left side modifiedInterval.begin = end; } else if (shrinkEnd) { // Shrink from right side modifiedInterval.end = begin; } else { // Make a hole uint64 oldEnd = modifiedInterval.end; modifiedInterval.end = begin; modifiedInterval.next = _insert( self, index, modifiedInterval.next, end, oldEnd, true ); newInterval = modifiedInterval.next; } } function _insert( Data storage self, uint64 prev, uint64 next, uint64 begin, uint64 end, bool allowGapAfterLast ) private returns(uint64 id) { require(begin < end, "right bound less or equal to left bound"); require((prev != 0 || next != 0) == (self.firstIndex > 0), "prev and next could be zero iff no intervals"); if (!isInitialized(self)) { initialize(self); } Interval storage prevInterval = self.intervals[prev]; Interval storage nextInterval = self.intervals[next]; require(prev == 0 || begin >= prevInterval.end, "begin could not intersect prev interval"); require(next == 0 || end <= nextInterval.begin, "end could not intersect next interval"); if ((prev > 0) == (next > 0)) { // Adding between existing intervals or very first interval require( prevInterval.next == next && nextInterval.prev == prev, "prev and next should refer to the neighboring intervals" ); } else if (next > 0) { // Adding before first interval require( self.firstIndex == next && nextInterval.prev == 0, "next should refer to the first interval" ); } else if (prev > 0) { // Adding after last interval require( self.lastIndex == prev && prevInterval.next == 0, "prev should refer to the last interval" ); require( allowGapAfterLast || prev != self.lastIndex || prevInterval.end == begin, "should begin from the end of latest interval when adding to the end" ); } bool concatPrev = (prev > 0 && begin == prevInterval.end); bool concatNext = (next > 0 && end == nextInterval.begin); if (!concatPrev && !concatNext) { id = uint64(self.intervals.length); self.intervals.push(Interval({ begin: begin, end: end, prev: prev, next: next })); if (next > 0) { nextInterval.prev = id; } else { self.lastIndex = id; } if (prev > 0) { prevInterval.next = id; } else { self.firstIndex = id; } } else if (concatPrev && concatNext) { prevInterval.end = nextInterval.end; prevInterval.next = nextInterval.next; id = prev; // When attaching pre last to last if (next == self.lastIndex) { self.lastIndex = id; } else { self.intervals[nextInterval.next].prev = id; } delete self.intervals[next]; } else if (concatPrev) { prevInterval.end = end; id = prev; } else if (concatNext) { nextInterval.begin = begin; id = next; } } } // File: contracts/SafeMath32.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath32 { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint32 a, uint32 b) internal pure returns (uint32) { // 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; } uint32 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint32 a, uint32 b) internal pure returns (uint32) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint32 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint32 a, uint32 b) internal pure returns (uint32) { require(b <= a); uint32 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint32 a, uint32 b) internal pure returns (uint32) { require(b != 0); return a % b; } } // File: contracts/SumMerkleProof.sol library SumMerkleProof { using SafeMath32 for uint32; // here is 32-bit plasma struct Slice { uint32 begin; uint32 end; } // @dev data ordered from leaves to root. // @dev index bits: right bit correspond leaves struct Proof { uint32 index; Slice slice; address item; bytes data; } function item(bytes memory proof, uint i) internal pure returns(uint32 length, address result) { // solium-disable-next-line security/no-inline-assembly assembly { length := div( mload( add( proof, // 12 = index + begin + end // 20 = item (address) // 32 = 12 + 20 add(32, mul(i, 24)) ) ), // Start from data offset, shift right to 28 bytes and return 4 0x100000000000000000000000000000000000000000000000000000000 ) result := div( mload( add( proof, // 12 = index + begin + end // 20 = item (address) // 36 = 12 + 20 + 4 (slice len offset) add(36, mul(i, 24)) ) ), // Start from data offset + 4, shift right to 12 bytes and return first 20 0x1000000000000000000000000 ) } } // @dev compute hash of the node from two child nodes function hash(uint32 l1, uint32 l2, address a1, address a2) internal pure returns(address) { return address(uint256(keccak256(abi.encodePacked(l1, l2, a1, a2)))); } function sumMerkleProof(Proof memory proof, address root, uint32 rootLength) internal pure returns(bool) { uint depth = proof.data.length / 24; uint32 curLength = proof.slice.end.sub(proof.slice.begin); address curItem = proof.item; uint32 curLeft = proof.slice.begin; uint32 index = proof.index; for(uint8 i = 0; i < depth; i++) { (uint32 length, address result) = item(proof.data, i); if (index & 1 == 1) { curItem = hash(length, curLength, result, curItem); curLeft = curLeft.sub(length); curLength = curLength.add(length); } else { curItem = hash(curLength, length, curItem, result); curLength = curLength.add(length); } index >>= 1; } return curLeft == 0 && curLength == rootLength && curItem == root; } } // File: solidity-rlp/contracts/RLPReader.sol /* * @author Hamdi Allam [email protected] * Please reach out with any questions or concerns */ pragma solidity ^0.5.0; library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded bytes */ function size(RLPItem memory item) internal pure returns (uint) { return item.len; } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) { require(isList(item)); uint items = numItems(item); result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if (item.len == 0) return false; uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix according to RLP spec require(item.len <= 21); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint) { require(item.len > 0); uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint memPtr = item.memPtr + offset; uint result; assembly { result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint) { if (item.len == 0) return 0; uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) private pure returns (uint len) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 1; else if (byte0 < STRING_LONG_START) return byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len len := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { return byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length len := add(dataLen, add(byteLen, 1)) } } } // @return number of bytes until the data function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } // File: contracts/PlasmaDecoder.sol library PlasmaDecoder { using RLPReader for RLPReader.RLPItem; using RLPReader for bytes; struct Input { address payable owner; uint32 blockIndex; uint32 txIndex; uint8 outputIndex; address assetId; uint64 begin; uint64 end; } struct Output { address payable owner; address assetId; uint64 begin; uint64 end; } struct Metadata { uint32 maxBlockId; } struct Signature { uint256 r; uint256 s; uint8 v; } struct Transaction { Input[] inputs; Output[] outputs; Metadata metadata; Signature[] signatures; } struct Block { uint32 blockNumber; uint256 previousBlockHash; uint256 merkleRoot; Signature signature; Transaction[] transactions; } function decodeProof(bytes memory rlpBytes) internal pure returns(SumMerkleProof.Proof memory) { return _decodeProof(rlpBytes.toRlpItem().toList()); } function decodeInput(bytes memory rlpBytes) internal pure returns(Input memory) { return _decodeInput(rlpBytes.toRlpItem().toList()); } function decodeOutput(bytes memory rlpBytes) internal pure returns(Output memory) { return _decodeOutput(rlpBytes.toRlpItem().toList()); } function decodeMetadata(bytes memory rlpBytes) internal pure returns(Metadata memory) { return _decodeMetadata(rlpBytes.toRlpItem().toList()); } function decodeSignature(bytes memory rlpBytes) internal pure returns(Signature memory) { return _decodeSignature(rlpBytes.toRlpItem().toList()); } function decodeTransaction(bytes memory rlpBytes) internal pure returns(Transaction memory) { return _decodeTransaction(rlpBytes.toRlpItem().toList()); } function decodeBlock(bytes memory rlpBytes) internal pure returns(Block memory) { return _decodeBlock(rlpBytes.toRlpItem().toList()); } // Private methods // here is 32-bit plasma struct Slice { uint32 begin; uint32 end; } // @dev data ordered from leaves to root. // @dev index bits: right bit correspond leaves struct Proof { uint32 index; Slice slice; address item; bytes data; } function _decodeSlice(RLPReader.RLPItem[] memory items) private pure returns(SumMerkleProof.Slice memory) { return SumMerkleProof.Slice({ begin: uint32(items[0].toUint()), end: uint32(items[1].toUint()) }); } function _decodeProof(RLPReader.RLPItem[] memory items) private pure returns(SumMerkleProof.Proof memory) { return SumMerkleProof.Proof({ index: uint32(items[0].toUint()), slice: _decodeSlice(items[1].toList()), item: items[2].toAddress(), data: items[3].toBytes() }); } function _decodeInput(RLPReader.RLPItem[] memory items) private pure returns(Input memory) { return Input({ owner: address(uint160(items[0].toAddress())), blockIndex: uint32(items[1].toUint()), txIndex: uint32(items[2].toUint()), outputIndex: uint8(items[3].toUint()), assetId: items[4].toAddress(), begin: uint64(items[5].toUint()), end: uint64(items[6].toUint()) }); } function _decodeInputs(RLPReader.RLPItem[] memory items) private pure returns(Input[] memory) { Input[] memory inputs = new Input[](items.length); for (uint i = 0; i < items.length; i++) { inputs[i] = _decodeInput(items[i].toList()); } return inputs; } function _decodeOutput(RLPReader.RLPItem[] memory items) private pure returns(Output memory) { return Output({ owner: address(uint160(items[0].toAddress())), assetId: items[1].toAddress(), begin: uint64(items[2].toUint()), end: uint64(items[3].toUint()) }); } function _decodeOutputs(RLPReader.RLPItem[] memory items) private pure returns(Output[] memory) { Output[] memory outputs = new Output[](items.length); for (uint i = 0; i < items.length; i++) { outputs[i] = _decodeOutput(items[i].toList()); } return outputs; } function _decodeMetadata(RLPReader.RLPItem[] memory items) private pure returns(Metadata memory) { return Metadata({ maxBlockId: uint32(items[0].toUint()) }); } function _decodeSignature(RLPReader.RLPItem[] memory items) internal pure returns(Signature memory) { return Signature({ r: items[0].toUint(), s: items[0].toUint(), v: uint8(items[0].toUint()) }); } function _decodeSignatures(RLPReader.RLPItem[] memory items) private pure returns(Signature[] memory) { Signature[] memory signatures = new Signature[](items.length); for (uint i = 0; i < items.length; i++) { signatures[i] = _decodeSignature(items[i].toList()); } return signatures; } function _decodeTransaction(RLPReader.RLPItem[] memory items) private pure returns(Transaction memory) { return Transaction({ inputs: _decodeInputs(items[0].toList()), outputs: _decodeOutputs(items[1].toList()), metadata: _decodeMetadata(items[2].toList()), signatures: _decodeSignatures(items[3].toList()) }); } function _decodeTransactions(RLPReader.RLPItem[] memory items) private pure returns(Transaction[] memory) { Transaction[] memory transactions = new Transaction[](items.length); for (uint i = 0; i < items.length; i++) { transactions[i] = _decodeTransaction(items[i].toList()); } return transactions; } function _decodeBlock(RLPReader.RLPItem[] memory items) private pure returns(Block memory) { return Block({ blockNumber: uint32(items[0].toUint()), previousBlockHash: items[1].toUint(), merkleRoot: items[2].toUint(), signature: _decodeSignature(items[3].toList()), transactions: _decodeTransactions(items[4].toList()) }); } } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol /** * @title Elliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // 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))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ 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)); } } // File: contracts/PlasmaBlocks.sol contract PlasmaBlocks is Ownable { using SafeMath for uint256; address[] private _blocks; event BlocksSubmitted(uint256 indexed length, uint256 time); function blocksLength() public view returns(uint) { return _blocks.length; } function blocks(uint i) public view returns(address) { return _blocks[i]; } function submitBlocks( uint256 fromIndex, bytes memory newBlocks ) public onlyOwner returns(uint256) { _submitBlocks(fromIndex, newBlocks); } function submitBlocksSigned( uint256 fromIndex, bytes memory newBlocks, bytes memory rsv ) public returns(uint256) { bytes32 messageHash = keccak256( abi.encodePacked( fromIndex, newBlocks ) ); bytes32 signedHash = ECDSA.toEthSignedMessageHash(messageHash); require(owner() == ECDSA.recover(signedHash, rsv), "Invalid signature"); return _submitBlocks(fromIndex, newBlocks); } function _submitBlocks( uint256 fromIndex, bytes memory newBlocks ) internal returns(uint256) { uint256 newBlocksLength = newBlocks.length / 20; require(fromIndex == _blocks.length, "Invalid fromIndex"); uint256 begin = _blocks.length.sub(fromIndex); _blocks.length = fromIndex.add(newBlocksLength); for (uint i = begin; i < newBlocksLength; i++) { address newBlock; uint256 offset = 32 + i * 20; // solium-disable-next-line security/no-inline-assembly assembly { // Load the current element of the proof newBlock := div(mload(add(newBlocks, offset)), 0x1000000000000000000000000) } _blocks[fromIndex + i] = newBlock; } if (begin < newBlocksLength) { // solium-disable-next-line security/no-block-members emit BlocksSubmitted(_blocks.length, block.timestamp); } return newBlocksLength - begin; } } // File: contracts/PlasmaAssets.sol contract PlasmaAssets is Ownable, PlasmaBlocks { using SafeMath for uint256; using SafeERC20 for IERC20; using PlasmaDecoder for bytes; using OrderedIntervalList for OrderedIntervalList.Data; using SumMerkleProof for SumMerkleProof.Proof; address constant public MAIN_COIN_ASSET_ID = address(0); address constant public ERC721_ASSET_ID = address(1); uint256 constant public ASSET_DECIMALS_TRUNCATION = 10e13; //TODO: will be different for tokens uint32 constant public PLASMA_ASSETS_TOTAL_SIZE = 2 ** 24 - 1; bytes32 private _expectedTokenAndTokenIdHash; mapping(address => uint256) private _assetOffsets; mapping(address => OrderedIntervalList.Data) private _assetLists; mapping(address => bytes32[]) private _allDepositHashes; mapping(bytes32 => bool) private _allWithdrawalHashes; mapping(bytes32 => bool) private _erc721Deposits; event AssetDeposited( address indexed token, address indexed who, uint64 intervalId, uint64 begin, uint64 end ); event CoinDeposited( address indexed who, uint256 amount ); event ERC20Deposited( address indexed token, address indexed who, uint256 amount ); event ERC721Deposited( address indexed token, address indexed who, uint256 tokenId, uint64 indexed begin ); event WithdrawalBegin( address owner, uint32 blockIndex, uint32 txIndex, uint8 outputIndex, address assetId, uint64 begin, uint64 end ); // constructor() public { _assetLists[MAIN_COIN_ASSET_ID].initialize(); _assetLists[ERC721_ASSET_ID].initialize(); } function assetOffsets(address asset) public view returns (uint256) { return _assetOffsets[asset]; } function setAssetOffset(address asset, uint256 assetOffset) public onlyOwner { require(assetOffset > uint(ERC721_ASSET_ID) && assetOffset < 256, "assetOffset should be in range [2, 255]"); require(_assetOffsets[asset] == 0, "assetOffset was already set"); _assetOffsets[asset] = assetOffset; _assetLists[asset].initialize(); } // Deposits function deposit() public payable { uint64 amount = uint64(msg.value / ASSET_DECIMALS_TRUNCATION); (uint64 intervalId, uint64 begin, uint64 end) = _assetLists[MAIN_COIN_ASSET_ID].append(amount); emit CoinDeposited(msg.sender, amount); emit AssetDeposited(MAIN_COIN_ASSET_ID, msg.sender, intervalId, begin, end); bytes32 hash = keccak256(abi.encodePacked(msg.sender, amount)); _allDepositHashes[msg.sender].push(hash); } function depositERC20(IERC20 token, uint256 amountArg) public { require(_assetLists[address(token)].isInitialized(), "Operator should add this token first"); uint64 amount = uint64(amountArg / ASSET_DECIMALS_TRUNCATION); (uint64 intervalId, uint64 begin, uint64 end) = _assetLists[address(token)].append(amount); uint256 preBalance = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), amount); uint256 deposited = token.balanceOf(address(this)).sub(preBalance); emit ERC20Deposited(address(token), msg.sender, deposited); emit AssetDeposited(address(token), msg.sender, intervalId, begin, end); bytes32 hash = keccak256(abi.encodePacked(token, msg.sender, intervalId, begin, end)); _allDepositHashes[msg.sender].push(hash); } function depositERC721(IERC721 token, uint256 tokenId) public { _expectedTokenAndTokenIdHash = keccak256(abi.encodePacked(token, tokenId)); token.safeTransferFrom(msg.sender, address(this), tokenId); require(_expectedTokenAndTokenIdHash == bytes32(0), "ERC721 token not received"); (uint64 intervalId, uint64 begin, uint64 end) = _assetLists[ERC721_ASSET_ID].append(1); emit ERC721Deposited(address(token), msg.sender, tokenId, begin); emit AssetDeposited(ERC721_ASSET_ID, msg.sender, intervalId, begin, end); bytes32 hash = keccak256(abi.encodePacked(ERC721_ASSET_ID, msg.sender, intervalId, begin, end)); _allDepositHashes[msg.sender].push(hash); bytes32 erc721Hash = keccak256(abi.encodePacked(token, tokenId, begin)); _erc721Deposits[erc721Hash] = true; } function onERC721Received( address operator, address /*from*/, uint256 tokenId, bytes memory /*data*/ ) public returns (bytes4) { bytes32 receivedTokenAndTokenId = keccak256(abi.encodePacked(msg.sender, tokenId)); require(operator == address(this), "Only this contract should deposit ERC721 tokens"); require(receivedTokenAndTokenId == _expectedTokenAndTokenIdHash, "ERC721 token was not expected"); delete _expectedTokenAndTokenIdHash; return this.onERC721Received.selector; } // Withdrawals function withdrawalBegin( bytes memory inputBytes // PlasmaDecoder.Input ) public payable //TODO: Bonds returns (bool) { PlasmaDecoder.Input memory input = inputBytes.decodeInput(); emit WithdrawalBegin( input.owner, input.blockIndex, input.txIndex, input.outputIndex, input.assetId, input.begin, input.end ); bytes32 inputHash = keccak256( abi.encodePacked( input.owner, input.blockIndex, input.txIndex, input.outputIndex, input.assetId, input.begin, input.end )); _allWithdrawalHashes[inputHash] = true; return true; } function withdrawalChallangeSpend( bytes memory inputBytes, // PlasmaDecoder.Input bytes memory txProofBytes, // SumMerkleProof.Proof uint64 blockIndex, uint8 /*spendIndex*/ ) public returns (bool) { PlasmaDecoder.Input memory input = inputBytes.decodeInput(); SumMerkleProof.Proof memory txProof = txProofBytes.decodeProof(); bytes32 inputHash = keccak256( abi.encodePacked( input.owner, input.blockIndex, input.txIndex, input.outputIndex, input.assetId, input.begin, input.end )); require(_allWithdrawalHashes[inputHash], "You should start withdrawal first"); require(txProof.sumMerkleProof(blocks(blockIndex), PLASMA_ASSETS_TOTAL_SIZE)); // Cancel widthraw delete _allWithdrawalHashes[inputHash]; return true; } // function withdrawalChallangeExistance( // ExitState state, // SumMerkleProof txProof, // MerkleProof inputProof, // uint64 maxBlockIndex, // MerkleProof maxBlockIndexProof // ) // public // returns(bool) // { // } function withdrawalEnd( bytes memory inputBytes, // PlasmaDecoder.Input uint64 intervalId, address token, uint256 tokenId ) public { PlasmaDecoder.Input memory input = inputBytes.decodeInput(); bytes32 inputHash = keccak256( abi.encodePacked( input.owner, input.blockIndex, input.txIndex, input.outputIndex, input.assetId, input.begin, input.end )); require(_allWithdrawalHashes[inputHash], "You should start withdrawal first"); delete _allWithdrawalHashes[inputHash]; // Update interval and check it exist _assetLists[input.assetId].remove(intervalId, input.begin, input.end); if (input.assetId == MAIN_COIN_ASSET_ID) { input.owner.transfer(uint256(input.end).sub(input.begin).mul(ASSET_DECIMALS_TRUNCATION)); return; } if (input.assetId == ERC721_ASSET_ID) { require(input.end == input.begin + 1, "It is allowed to withdraw only 1 ERC721 per transaction"); bytes32 depositHash = keccak256(abi.encodePacked(token, tokenId, input.begin)); require(_erc721Deposits[depositHash], "Invalid token or tokeId arguments"); delete _erc721Deposits[depositHash]; IERC721(token).approve(msg.sender, tokenId); return; } IERC20(token).transfer(msg.sender, uint256(input.end).sub(input.begin)); } } // File: contracts/BankexPlasma.sol // solium-disable-next-line no-empty-blocks contract BankexPlasma is PlasmaAssets { }
solium-disable-next-line no-empty-blocks
contract BankexPlasma is PlasmaAssets { }
882,506
[ 1, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 5531, 17, 7996, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 25610, 338, 1749, 345, 2540, 353, 3008, 345, 2540, 10726, 288, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at BscScan.com on 2021-07-02 */ // File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/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() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @pancakeswap\pancake-swap-lib\contracts\math\SafeMath.sol pragma solidity >=0.4.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; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal 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; } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @openzeppelin/contracts/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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/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' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require( oldAllowance >= value, "SafeERC20: decreased allowance below zero" ); uint256 newAllowance = oldAllowance - value; _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/interfaces/IRandomNumberGenerator.sol pragma solidity ^0.8.4; interface IRandomNumberGenerator { /** * Requests randomness from a user-provided seed */ function getRandomNumber(uint256 _seed) external; /** * View latest lotteryId numbers */ function viewLatestLotteryId() external view returns (uint256); /** * Views random result */ function viewRandomResult() external view returns (uint32); } // File: contracts/interfaces/IBirbLottery.sol pragma solidity ^0.8.4; interface IBirbLottery { /** * @notice Buy tickets for the current lottery * @param _lotteryId: lotteryId * @param _ticketNumbers: array of ticket numbers between 1,000,000 and 1,999,999 * @dev Callable by users */ function buyTickets(uint256 _lotteryId, uint32[] calldata _ticketNumbers) external; /** * @notice Claim a set of winning tickets for a lottery * @param _lotteryId: lottery id * @param _ticketIds: array of ticket ids * @param _brackets: array of brackets for the ticket ids * @dev Callable by users only, not contract! */ function claimTickets( uint256 _lotteryId, uint256[] calldata _ticketIds, uint32[] calldata _brackets ) external; /** * @notice Close lottery * @param _lotteryId: lottery id * @dev Callable by operator */ function closeLottery(uint256 _lotteryId) external; /** * @notice Draw the final number, calculate reward in BIRB per group, and make lottery claimable * @param _lotteryId: lottery id * @param _autoInjection: reinjects funds into next lottery (vs. withdrawing all) * @dev Callable by operator */ function drawFinalNumberAndMakeLotteryClaimable( uint256 _lotteryId, bool _autoInjection ) external; /** * @notice Inject funds * @param _lotteryId: lottery id * @param _amount: amount to inject in BIRB token * @dev Callable by operator */ function injectFunds(uint256 _lotteryId, uint256 _amount) external; /** * @notice Start the lottery * @dev Callable by operator * @param _endTime: endTime of the lottery * @param _priceTicketInBirb: price of a ticket in BIRB * @param _discountDivisor: the divisor to calculate the discount magnitude for bulks * @param _rewardsBreakdown: breakdown of rewards per bracket (must sum to 10,000) * @param _treasuryFee: treasury fee (10,000 = 100%, 100 = 1%) */ function startLottery( uint256 _endTime, uint256 _priceTicketInBirb, uint256 _discountDivisor, uint256[6] calldata _rewardsBreakdown, uint256 _treasuryFee ) external; /** * @notice View current lottery id */ function viewCurrentLotteryId() external returns (uint256); } // File: contracts/BirbLottery.sol pragma solidity ^0.8.4; pragma abicoder v2; /** @title BirbSwap Lottery. * @notice It is a contract for a lottery system using * randomness provided externally. */ contract BirbLottery is ReentrancyGuard, IBirbLottery, Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; address public injectorAddress; address public operatorAddress; address public treasuryAddress; uint256 public currentLotteryId; uint256 public currentTicketId; uint256 public maxNumberTicketsPerBuyOrClaim = 100; uint256 public maxPriceTicketInBirb = 50 ether; uint256 public minPriceTicketInBirb = 0.005 ether; uint256 public pendingInjectionNextLottery; uint256 public constant MIN_DISCOUNT_DIVISOR = 300; uint256 public constant MIN_LENGTH_LOTTERY = 4 hours - 5 minutes; // 4 hours uint256 public constant MAX_LENGTH_LOTTERY = 4 days + 5 minutes; // 4 days uint256 public constant MAX_TREASURY_FEE = 3000; // 30% IERC20 public birbToken; IRandomNumberGenerator public randomGenerator; enum Status { Pending, Open, Close, Claimable } struct Lottery { Status status; uint256 startTime; uint256 endTime; uint256 priceTicketInBirb; uint256 discountDivisor; uint256[6] rewardsBreakdown; // 0: 1 matching number // 5: 6 matching numbers uint256 treasuryFee; // 500: 5% // 200: 2% // 50: 0.5% uint256[6] birbPerBracket; uint256[6] countWinnersPerBracket; uint256 firstTicketId; uint256 firstTicketIdNextLottery; uint256 amountCollectedInBirb; uint32 finalNumber; } struct Ticket { uint32 number; address owner; } // Mapping are cheaper than arrays mapping(uint256 => Lottery) private _lotteries; mapping(uint256 => Ticket) private _tickets; // Bracket calculator is used for verifying claims for ticket prizes mapping(uint32 => uint32) private _bracketCalculator; // Keeps track of number of ticket per unique combination for each lotteryId mapping(uint256 => mapping(uint32 => uint256)) private _numberTicketsPerLotteryId; // Keep track of user ticket ids for a given lotteryId mapping(address => mapping(uint256 => uint256[])) private _userTicketIdsPerLotteryId; modifier notContract() { require(!_isContract(msg.sender), "Contract not allowed"); require(msg.sender == tx.origin, "Proxy contract not allowed"); _; } modifier onlyOperator() { require(msg.sender == operatorAddress, "Not operator"); _; } modifier onlyOwnerOrInjector() { require( (msg.sender == owner()) || (msg.sender == injectorAddress), "Not owner or injector" ); _; } event AdminTokenRecovery(address token, uint256 amount); event LotteryClose( uint256 indexed lotteryId, uint256 firstTicketIdNextLottery ); event LotteryInjection(uint256 indexed lotteryId, uint256 injectedAmount); event LotteryOpen( uint256 indexed lotteryId, uint256 startTime, uint256 endTime, uint256 priceTicketInBirb, uint256 firstTicketId, uint256 injectedAmount ); event LotteryNumberDrawn( uint256 indexed lotteryId, uint256 finalNumber, uint256 countWinningTickets ); event NewOperatorAndTreasuryAndInjectorAddresses( address operator, address treasury, address injector ); event NewRandomGenerator(address indexed randomGenerator); event TicketsPurchase( address indexed buyer, uint256 indexed lotteryId, uint256 numberTickets ); event TicketsClaim( address indexed claimer, uint256 amount, uint256 indexed lotteryId, uint256 numberTickets ); /** * @notice Constructor * @dev RandomNumberGenerator must be deployed prior to this contract * @param _birbTokenAddress: address of the BIRB token * @param _randomGeneratorAddress: address of the RandomGenerator contract used to work with ChainLink VRF */ constructor(address _birbTokenAddress, address _randomGeneratorAddress) { birbToken = IERC20(_birbTokenAddress); randomGenerator = IRandomNumberGenerator(_randomGeneratorAddress); // Initializes a mapping _bracketCalculator[0] = 1; _bracketCalculator[1] = 11; _bracketCalculator[2] = 111; _bracketCalculator[3] = 1111; _bracketCalculator[4] = 11111; _bracketCalculator[5] = 111111; } /** * @notice Buy tickets for the current lottery * @param _lotteryId: lotteryId * @param _ticketNumbers: array of ticket numbers between 1,000,000 and 1,999,999 * @dev Callable by users */ function buyTickets(uint256 _lotteryId, uint32[] calldata _ticketNumbers) external override notContract nonReentrant { require(_ticketNumbers.length != 0, "No ticket specified"); require( _ticketNumbers.length <= maxNumberTicketsPerBuyOrClaim, "Too many tickets" ); require( _lotteries[_lotteryId].status == Status.Open, "Lottery is not open" ); require( block.timestamp < _lotteries[_lotteryId].endTime, "Lottery is over" ); // Calculate number of BIRB to this contract uint256 amountBirbToTransfer = _calculateTotalPriceForBulkTickets( _lotteries[_lotteryId].discountDivisor, _lotteries[_lotteryId].priceTicketInBirb, _ticketNumbers.length ); // Transfer birb tokens to this contract uint256 balanceBefore = birbToken.balanceOf(address(this)); birbToken.safeTransferFrom( address(msg.sender), address(this), amountBirbToTransfer ); amountBirbToTransfer = birbToken.balanceOf(address(this)).sub( balanceBefore ); // Increment the total amount collected for the lottery round _lotteries[_lotteryId].amountCollectedInBirb = _lotteries[_lotteryId] .amountCollectedInBirb .add(amountBirbToTransfer); for (uint256 i = 0; i < _ticketNumbers.length; i++) { uint32 thisTicketNumber = _ticketNumbers[i]; require( (thisTicketNumber >= 1000000) && (thisTicketNumber <= 1999999), "Outside range" ); _numberTicketsPerLotteryId[_lotteryId][ 1 + (thisTicketNumber % 10) ]++; _numberTicketsPerLotteryId[_lotteryId][ 11 + (thisTicketNumber % 100) ]++; _numberTicketsPerLotteryId[_lotteryId][ 111 + (thisTicketNumber % 1000) ]++; _numberTicketsPerLotteryId[_lotteryId][ 1111 + (thisTicketNumber % 10000) ]++; _numberTicketsPerLotteryId[_lotteryId][ 11111 + (thisTicketNumber % 100000) ]++; _numberTicketsPerLotteryId[_lotteryId][ 111111 + (thisTicketNumber % 1000000) ]++; _userTicketIdsPerLotteryId[msg.sender][_lotteryId].push( currentTicketId ); _tickets[currentTicketId] = Ticket({ number: thisTicketNumber, owner: msg.sender }); // Increase lottery ticket number currentTicketId++; } emit TicketsPurchase(msg.sender, _lotteryId, _ticketNumbers.length); } /** * @notice Claim a set of winning tickets for a lottery * @param _lotteryId: lottery id * @param _ticketIds: array of ticket ids * @param _brackets: array of brackets for the ticket ids * @dev Callable by users only, not contract! */ function claimTickets( uint256 _lotteryId, uint256[] calldata _ticketIds, uint32[] calldata _brackets ) external override notContract nonReentrant { require(_ticketIds.length == _brackets.length, "Not same length"); require(_ticketIds.length != 0, "Length must be >0"); require( _ticketIds.length <= maxNumberTicketsPerBuyOrClaim, "Too many tickets" ); require( _lotteries[_lotteryId].status == Status.Claimable, "Lottery not claimable" ); // Initializes the rewardInBirbToTransfer uint256 rewardInBirbToTransfer; for (uint256 i = 0; i < _ticketIds.length; i++) { require(_brackets[i] < 6, "Bracket out of range"); // Must be between 0 and 5 uint256 thisTicketId = _ticketIds[i]; require( _lotteries[_lotteryId].firstTicketIdNextLottery > thisTicketId, "TicketId too high" ); require( _lotteries[_lotteryId].firstTicketId <= thisTicketId, "TicketId too low" ); require( msg.sender == _tickets[thisTicketId].owner, "Not the owner" ); // Update the lottery ticket owner to 0x address _tickets[thisTicketId].owner = address(0); uint256 rewardForTicketId = _calculateRewardsForTicketId( _lotteryId, thisTicketId, _brackets[i] ); // Check user is claiming the correct bracket require(rewardForTicketId != 0, "No prize for this bracket"); if (_brackets[i] != 5) { require( _calculateRewardsForTicketId( _lotteryId, thisTicketId, _brackets[i] + 1 ) == 0, "Bracket must be higher" ); } // Increment the reward to transfer rewardInBirbToTransfer += rewardForTicketId; } // Transfer money to msg.sender birbToken.safeTransfer(msg.sender, rewardInBirbToTransfer); emit TicketsClaim( msg.sender, rewardInBirbToTransfer, _lotteryId, _ticketIds.length ); } /** * @notice Close lottery * @param _lotteryId: lottery id * @dev Callable by operator */ function closeLottery(uint256 _lotteryId) external override onlyOperator nonReentrant { require( _lotteries[_lotteryId].status == Status.Open, "Lottery not open" ); require( block.timestamp > _lotteries[_lotteryId].endTime, "Lottery not over" ); _lotteries[_lotteryId].firstTicketIdNextLottery = currentTicketId; // Request a random number from the generator based on a seed randomGenerator.getRandomNumber( uint256(keccak256(abi.encodePacked(_lotteryId, currentTicketId))) ); _lotteries[_lotteryId].status = Status.Close; emit LotteryClose(_lotteryId, currentTicketId); } /** * @notice Draw the final number, calculate reward in BIRB per group, and make lottery claimable * @param _lotteryId: lottery id * @param _autoInjection: reinjects funds into next lottery (vs. withdrawing all) * @dev Callable by operator */ function drawFinalNumberAndMakeLotteryClaimable( uint256 _lotteryId, bool _autoInjection ) external override onlyOperator nonReentrant { require( _lotteries[_lotteryId].status == Status.Close, "Lottery not close" ); require( _lotteryId == randomGenerator.viewLatestLotteryId(), "Numbers not drawn" ); // Calculate the finalNumber based on the randomResult generated by ChainLink's fallback uint32 finalNumber = randomGenerator.viewRandomResult(); // Initialize a number to count addresses in the previous bracket uint256 numberAddressesInPreviousBracket; // Calculate the amount to share post-treasury fee uint256 amountToShareToWinners = ( ((_lotteries[_lotteryId].amountCollectedInBirb) * (10000 - _lotteries[_lotteryId].treasuryFee)) ) / 10000; // Initializes the amount to withdraw to treasury uint256 amountToWithdrawToTreasury; // Calculate prizes in BIRB for each bracket by starting from the highest one for (uint32 i = 0; i < 6; i++) { uint32 j = 5 - i; uint32 transformedWinningNumber = _bracketCalculator[j] + (finalNumber % (uint32(10)**(j + 1))); _lotteries[_lotteryId].countWinnersPerBracket[j] = _numberTicketsPerLotteryId[_lotteryId][ transformedWinningNumber ] - numberAddressesInPreviousBracket; // A. If number of users for this _bracket number is superior to 0 if ( (_numberTicketsPerLotteryId[_lotteryId][ transformedWinningNumber ] - numberAddressesInPreviousBracket) != 0 ) { // B. If rewards at this bracket are > 0, calculate, else, report the numberAddresses from previous bracket if (_lotteries[_lotteryId].rewardsBreakdown[j] != 0) { _lotteries[_lotteryId].birbPerBracket[j] = ((_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) / (_numberTicketsPerLotteryId[_lotteryId][ transformedWinningNumber ] - numberAddressesInPreviousBracket)) / 10000; // Update numberAddressesInPreviousBracket numberAddressesInPreviousBracket = _numberTicketsPerLotteryId[ _lotteryId ][transformedWinningNumber]; } // A. No BIRB to distribute, they are added to the amount to withdraw to treasury address } else { _lotteries[_lotteryId].birbPerBracket[j] = 0; amountToWithdrawToTreasury += (_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) / 10000; } } // Update internal statuses for lottery _lotteries[_lotteryId].finalNumber = finalNumber; _lotteries[_lotteryId].status = Status.Claimable; if (_autoInjection) { pendingInjectionNextLottery = amountToWithdrawToTreasury; amountToWithdrawToTreasury = 0; } amountToWithdrawToTreasury = amountToWithdrawToTreasury.add( _lotteries[_lotteryId].amountCollectedInBirb.sub( amountToShareToWinners ) ); // Transfer BIRB to treasury address if (amountToWithdrawToTreasury > 0) { birbToken.safeTransfer(treasuryAddress, amountToWithdrawToTreasury); } emit LotteryNumberDrawn( currentLotteryId, finalNumber, numberAddressesInPreviousBracket ); } /** * @notice Change the random generator * @dev The calls to functions are used to verify the new generator implements them properly. * It is necessary to wait for the VRF response before starting a round. * Callable only by the contract owner * @param _randomGeneratorAddress: address of the random generator */ function changeRandomGenerator(address _randomGeneratorAddress) external onlyOwner { require( _lotteries[currentLotteryId].status == Status.Claimable, "Lottery not in claimable" ); // Request a random number from the generator based on a seed IRandomNumberGenerator(_randomGeneratorAddress).getRandomNumber( uint256( keccak256(abi.encodePacked(currentLotteryId, currentTicketId)) ) ); // Calculate the finalNumber based on the randomResult generated by ChainLink's fallback IRandomNumberGenerator(_randomGeneratorAddress).viewRandomResult(); randomGenerator = IRandomNumberGenerator(_randomGeneratorAddress); emit NewRandomGenerator(_randomGeneratorAddress); } /** * @notice Inject funds * @param _lotteryId: lottery id * @param _amount: amount to inject in BIRB token * @dev Callable by owner or injector address */ function injectFunds(uint256 _lotteryId, uint256 _amount) external override onlyOwnerOrInjector { require( _lotteries[_lotteryId].status == Status.Open, "Lottery not open" ); uint256 balanceBefore = birbToken.balanceOf(address(this)); birbToken.safeTransferFrom(address(msg.sender), address(this), _amount); _amount = birbToken.balanceOf(address(this)).sub(balanceBefore); _lotteries[_lotteryId].amountCollectedInBirb = _lotteries[_lotteryId] .amountCollectedInBirb .add(_amount); emit LotteryInjection(_lotteryId, _amount); } /** * @notice Start the lottery * @dev Callable by operator * @param _endTime: endTime of the lottery * @param _priceTicketInBirb: price of a ticket in BIRB * @param _discountDivisor: the divisor to calculate the discount magnitude for bulks * @param _rewardsBreakdown: breakdown of rewards per bracket (must sum to 10,000) * @param _treasuryFee: treasury fee (10,000 = 100%, 100 = 1%) */ function startLottery( uint256 _endTime, uint256 _priceTicketInBirb, uint256 _discountDivisor, uint256[6] calldata _rewardsBreakdown, uint256 _treasuryFee ) external override onlyOperator { require( (currentLotteryId == 0) || (_lotteries[currentLotteryId].status == Status.Claimable), "Not time to start lottery" ); require( _endTime > block.timestamp && (_endTime.sub(block.timestamp) > MIN_LENGTH_LOTTERY) && (_endTime.sub(block.timestamp) < MAX_LENGTH_LOTTERY), "Lottery length outside of range" ); require( (_priceTicketInBirb >= minPriceTicketInBirb) && (_priceTicketInBirb <= maxPriceTicketInBirb), "Outside of limits" ); require( _discountDivisor >= MIN_DISCOUNT_DIVISOR, "Discount divisor too low" ); require(_treasuryFee <= MAX_TREASURY_FEE, "Treasury fee too high"); require( _rewardsBreakdown[0] .add(_rewardsBreakdown[1]) .add(_rewardsBreakdown[2]) .add(_rewardsBreakdown[3]) .add(_rewardsBreakdown[4]) .add(_rewardsBreakdown[5]) == 10000, "Rewards must equal 10000" ); currentLotteryId = currentLotteryId.add(1); _lotteries[currentLotteryId] = Lottery({ status: Status.Open, startTime: block.timestamp, endTime: _endTime, priceTicketInBirb: _priceTicketInBirb, discountDivisor: _discountDivisor, rewardsBreakdown: _rewardsBreakdown, treasuryFee: _treasuryFee, birbPerBracket: [ uint256(0), uint256(0), uint256(0), uint256(0), uint256(0), uint256(0) ], countWinnersPerBracket: [ uint256(0), uint256(0), uint256(0), uint256(0), uint256(0), uint256(0) ], firstTicketId: currentTicketId, firstTicketIdNextLottery: currentTicketId, amountCollectedInBirb: pendingInjectionNextLottery, finalNumber: 0 }); emit LotteryOpen( currentLotteryId, block.timestamp, _endTime, _priceTicketInBirb, currentTicketId, pendingInjectionNextLottery ); pendingInjectionNextLottery = 0; } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _tokenAddress: the address of the token to withdraw * @param _tokenAmount: the number of token amount to withdraw * @dev Only callable by owner. */ function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require(_tokenAddress != address(birbToken), "Cannot be BIRB token"); IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); } /** * @notice Set BIRB price ticket upper/lower limit * @dev Only callable by owner * @param _minPriceTicketInBirb: minimum price of a ticket in BIRB * @param _maxPriceTicketInBirb: maximum price of a ticket in BIRB */ function setMinAndMaxTicketPriceInBirb( uint256 _minPriceTicketInBirb, uint256 _maxPriceTicketInBirb ) external onlyOwner { require( _minPriceTicketInBirb <= _maxPriceTicketInBirb, "minPrice must be < maxPrice" ); minPriceTicketInBirb = _minPriceTicketInBirb; maxPriceTicketInBirb = _maxPriceTicketInBirb; } /** * @notice Set max number of tickets * @dev Only callable by owner */ function setMaxNumberTicketsPerBuy(uint256 _maxNumberTicketsPerBuy) external onlyOwner { require(_maxNumberTicketsPerBuy != 0, "Must be > 0"); maxNumberTicketsPerBuyOrClaim = _maxNumberTicketsPerBuy; } /** * @notice Set operator, treasury, and injector addresses * @dev Only callable by owner * @param _operatorAddress: address of the operator * @param _treasuryAddress: address of the treasury * @param _injectorAddress: address of the injector */ function setOperatorAndTreasuryAndInjectorAddresses( address _operatorAddress, address _treasuryAddress, address _injectorAddress ) external onlyOwner { require(_operatorAddress != address(0), "Cannot be zero address"); require(_treasuryAddress != address(0), "Cannot be zero address"); require(_injectorAddress != address(0), "Cannot be zero address"); operatorAddress = _operatorAddress; treasuryAddress = _treasuryAddress; injectorAddress = _injectorAddress; emit NewOperatorAndTreasuryAndInjectorAddresses( _operatorAddress, _treasuryAddress, _injectorAddress ); } /** * @notice Calculate price of a set of tickets * @param _discountDivisor: divisor for the discount * @param _priceTicket price of a ticket (in BIRB) * @param _numberTickets number of tickets to buy */ function calculateTotalPriceForBulkTickets( uint256 _discountDivisor, uint256 _priceTicket, uint256 _numberTickets ) external pure returns (uint256) { require( _discountDivisor >= MIN_DISCOUNT_DIVISOR, "Must be >= MIN_DISCOUNT_DIVISOR" ); require(_numberTickets != 0, "Number of tickets must be > 0"); return _calculateTotalPriceForBulkTickets( _discountDivisor, _priceTicket, _numberTickets ); } /** * @notice View current lottery id */ function viewCurrentLotteryId() external view override returns (uint256) { return currentLotteryId; } /** * @notice View lottery information * @param _lotteryId: lottery id */ function viewLottery(uint256 _lotteryId) external view returns (Lottery memory) { return _lotteries[_lotteryId]; } /** * @notice View ticker statuses and numbers for an array of ticket ids * @param _ticketIds: array of _ticketId */ function viewNumbersAndStatusesForTicketIds(uint256[] calldata _ticketIds) external view returns (uint32[] memory, bool[] memory) { uint256 length = _ticketIds.length; uint32[] memory ticketNumbers = new uint32[](length); bool[] memory ticketStatuses = new bool[](length); for (uint256 i = 0; i < length; i++) { ticketNumbers[i] = _tickets[_ticketIds[i]].number; if (_tickets[_ticketIds[i]].owner == address(0)) { ticketStatuses[i] = true; } else { ticketStatuses[i] = false; } } return (ticketNumbers, ticketStatuses); } /** * @notice View rewards for a given ticket, providing a bracket, and lottery id * @dev Computations are mostly offchain. This is used to verify a ticket! * @param _lotteryId: lottery id * @param _ticketId: ticket id * @param _bracket: bracket for the ticketId to verify the claim and calculate rewards */ function viewRewardsForTicketId( uint256 _lotteryId, uint256 _ticketId, uint32 _bracket ) external view returns (uint256) { // Check lottery is in claimable status if (_lotteries[_lotteryId].status != Status.Claimable) { return 0; } // Check ticketId is within range if ( (_lotteries[_lotteryId].firstTicketIdNextLottery < _ticketId) && (_lotteries[_lotteryId].firstTicketId >= _ticketId) ) { return 0; } return _calculateRewardsForTicketId(_lotteryId, _ticketId, _bracket); } /** * @notice View user ticket ids, numbers, and statuses of user for a given lottery * @param _user: user address * @param _lotteryId: lottery id * @param _cursor: cursor to start where to retrieve the tickets * @param _size: the number of tickets to retrieve */ function viewUserInfoForLotteryId( address _user, uint256 _lotteryId, uint256 _cursor, uint256 _size ) external view returns ( uint256[] memory, uint32[] memory, bool[] memory, uint256 ) { uint256 length = _size; uint256 numberTicketsBoughtAtLotteryId = _userTicketIdsPerLotteryId[ _user ][_lotteryId].length; if (length > numberTicketsBoughtAtLotteryId.sub(_cursor)) { length = numberTicketsBoughtAtLotteryId.sub(_cursor); } uint256[] memory lotteryTicketIds = new uint256[](length); uint32[] memory ticketNumbers = new uint32[](length); bool[] memory ticketStatuses = new bool[](length); for (uint256 i = 0; i < length; i++) { lotteryTicketIds[i] = _userTicketIdsPerLotteryId[_user][_lotteryId][ i.add(_cursor) ]; ticketNumbers[i] = _tickets[lotteryTicketIds[i]].number; // True = ticket claimed if (_tickets[lotteryTicketIds[i]].owner == address(0)) { ticketStatuses[i] = true; } else { // ticket not claimed (includes the ones that cannot be claimed) ticketStatuses[i] = false; } } return ( lotteryTicketIds, ticketNumbers, ticketStatuses, _cursor.add(length) ); } /** * @notice Calculate rewards for a given ticket * @param _lotteryId: lottery id * @param _ticketId: ticket id * @param _bracket: bracket for the ticketId to verify the claim and calculate rewards */ function _calculateRewardsForTicketId( uint256 _lotteryId, uint256 _ticketId, uint32 _bracket ) internal view returns (uint256) { // Retrieve the winning number combination uint32 userNumber = _lotteries[_lotteryId].finalNumber; // Retrieve the user number combination from the ticketId uint32 winningTicketNumber = _tickets[_ticketId].number; // Apply transformation to verify the claim provided by the user is true uint32 transformedWinningNumber = _bracketCalculator[_bracket] + (winningTicketNumber % (uint32(10)**(_bracket + 1))); uint32 transformedUserNumber = _bracketCalculator[_bracket] + (userNumber % (uint32(10)**(_bracket + 1))); // Confirm that the two transformed numbers are the same, if not throw if (transformedWinningNumber == transformedUserNumber) { return _lotteries[_lotteryId].birbPerBracket[_bracket]; } else { return 0; } } /** * @notice Calculate final price for bulk of tickets * @param _discountDivisor: divisor for the discount (the smaller it is, the greater the discount is) * @param _priceTicket: price of a ticket * @param _numberTickets: number of tickets purchased */ function _calculateTotalPriceForBulkTickets( uint256 _discountDivisor, uint256 _priceTicket, uint256 _numberTickets ) internal pure returns (uint256) { return (_priceTicket * _numberTickets * (_discountDivisor + 1 - _numberTickets)) / _discountDivisor; } /** * @notice Check if an address is a contract */ function _isContract(address _addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(_addr) } return size > 0; } }
Increment the reward to transfer
rewardInBirbToTransfer += rewardForTicketId;
12,751,289
[ 1, 10798, 326, 19890, 358, 7412, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 19890, 382, 38, 481, 70, 774, 5912, 1011, 19890, 1290, 13614, 548, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // Welcome To ZeroChain Network Airdrop // // send at least 0.0001 ETH to Smart Contract 0x7589e58B2197CA56BcD186c871D3c9aBdE35B737 // NOTE: do not forget to set the gas price 100,000 for the transaction to run smoothly // Symbol : OxCN // Name : ZeroChainNetwork // Total supply: 1,000,000,000 // Decimals : 18 //EXCHANGE: //while for the exchange, we have contacted some exchanges and we will probably be scheduled in the stock 4 days after the first stage 1 airdrop is done, this is the list of exchanges we managed to contact //1. Mercatox (negotiation) //2. idax (negotiation) //3. forkdelta (no response yet) //4. crex24 (negotiation) //5. bitebtc (negotiation) //6. idex (no response) //7. coinex (negotiation) //8. hitbtc (unconfirmed) //YOUR SUPPORT: //we appreciate your support, we are very excited and excited for all your support, // //supportive wallet: //-myetherwallet (online) //-metamask (extension) //-imtoken (Android) //-coinomi (Android) // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract OxChainNetwork is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public bonusEnds; uint public endDate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function OxChainNetwork() public { symbol = "OxCN"; name = "OxChain Network"; decimals = 18; bonusEnds = now + 1500 weeks; endDate = now + 7500 weeks; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner&#39;s account to `to` account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner&#39;s account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner&#39;s account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // 1,000 FWD Tokens per 1 ETH // ------------------------------------------------------------------------ function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 50000001; } else { tokens = msg.value * 14000000000000000000000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // 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); } }
------------------------------------------------------------------------ 1,000 FWD Tokens per 1 ETH ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 50000001; tokens = msg.value * 14000000000000000000000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); }
6,624,210
[ 1, 29461, 404, 16, 3784, 478, 16006, 13899, 1534, 404, 512, 2455, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1832, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3338, 1545, 12572, 597, 2037, 1648, 13202, 1769, 203, 3639, 2254, 2430, 31, 203, 3639, 309, 261, 3338, 1648, 324, 22889, 24980, 13, 288, 203, 5411, 2430, 273, 1234, 18, 1132, 380, 1381, 9449, 21, 31, 203, 5411, 2430, 273, 1234, 18, 1132, 380, 5045, 12648, 12648, 11706, 31, 203, 3639, 289, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 4183, 986, 12, 70, 26488, 63, 3576, 18, 15330, 6487, 2430, 1769, 203, 3639, 389, 4963, 3088, 1283, 273, 4183, 986, 24899, 4963, 3088, 1283, 16, 2430, 1769, 203, 3639, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 2430, 1769, 203, 3639, 3410, 18, 13866, 12, 3576, 18, 1132, 1769, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xa2a18225C976F4bc1d5192E2ade2C29dEefcE635/sources/src/interfaces/IStrategyRegistry.sol
* @notice Group of platform fees. @custom:member ecosystemFeeReciever Receiver of the ecosystem fees. @custom:member ecosystemFeePct Ecosystem fees. Expressed in FULL_PERCENT. @custom:member treasuryFeeReciever Receiver of the treasury fees. @custom:member treasuryFeePct Treasury fees. Expressed in FULL_PERCENT./
struct PlatformFees { address ecosystemFeeReceiver; uint96 ecosystemFeePct; address treasuryFeeReceiver; uint96 treasuryFeePct; }
15,677,530
[ 1, 1114, 434, 4072, 1656, 281, 18, 632, 3662, 30, 5990, 6557, 538, 1108, 14667, 5650, 1385, 502, 31020, 434, 326, 6557, 538, 1108, 1656, 281, 18, 632, 3662, 30, 5990, 6557, 538, 1108, 14667, 52, 299, 512, 14445, 1108, 1656, 281, 18, 7784, 4638, 316, 18153, 67, 3194, 19666, 18, 632, 3662, 30, 5990, 9787, 345, 22498, 14667, 5650, 1385, 502, 31020, 434, 326, 9787, 345, 22498, 1656, 281, 18, 632, 3662, 30, 5990, 9787, 345, 22498, 14667, 52, 299, 399, 266, 345, 22498, 1656, 281, 18, 7784, 4638, 316, 18153, 67, 3194, 19666, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1697, 11810, 2954, 281, 288, 203, 565, 1758, 6557, 538, 1108, 14667, 12952, 31, 203, 565, 2254, 10525, 6557, 538, 1108, 14667, 52, 299, 31, 203, 565, 1758, 9787, 345, 22498, 14667, 12952, 31, 203, 565, 2254, 10525, 9787, 345, 22498, 14667, 52, 299, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.13; import "./libraries/SafeMath.sol"; import "./libraries/SafeERC20.sol"; import "./interfaces/IOwnable.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IERC20Metadata.sol"; import "./interfaces/IOHM.sol"; import "./interfaces/IsOHM.sol"; import "./interfaces/IBondingCalculator.sol"; import "./interfaces/ITreasury.sol"; import "./types/OlympusAccessControlled.sol"; contract OlympusTreasury is OlympusAccessControlled, ITreasury { /* ========== DEPENDENCIES ========== */ using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== EVENTS ========== */ event Deposit(address indexed token, uint256 amount, uint256 value); event Withdrawal(address indexed token, uint256 amount, uint256 value); event CreateDebt( address indexed debtor, address indexed token, uint256 amount, uint256 value ); event RepayDebt( address indexed debtor, address indexed token, uint256 amount, uint256 value ); event Managed(address indexed token, uint256 amount); event ReservesAudited(uint256 indexed totalReserves); event Minted( address indexed caller, address indexed recipient, uint256 amount ); event PermissionQueued(STATUS indexed status, address queued); event Permissioned(address addr, STATUS indexed status, bool result); /* ========== DATA STRUCTURES ========== */ enum STATUS { RESERVEDEPOSITOR, RESERVESPENDER, RESERVETOKEN, RESERVEMANAGER, LIQUIDITYDEPOSITOR, LIQUIDITYTOKEN, LIQUIDITYMANAGER, RESERVEDEBTOR, REWARDMANAGER, SOHM, OHMDEBTOR } struct Queue { STATUS managing; address toPermit; address calculator; uint256 timelockEnd; bool nullify; bool executed; } /* ========== STATE VARIABLES ========== */ IOHM public immutable OHM; IsOHM public sOHM; mapping(STATUS => address[]) public registry; mapping(STATUS => mapping(address => bool)) public permissions; mapping(address => address) public bondCalculator; mapping(address => uint256) public debtLimit; uint256 public totalReserves; uint256 public totalDebt; uint256 public ohmDebt; Queue[] public permissionQueue; uint256 public immutable blocksNeededForQueue; bool public timelockEnabled; bool public initialized; uint256 public onChainGovernanceTimelock; string internal notAccepted = "Treasury: not accepted"; string internal notApproved = "Treasury: not approved"; string internal invalidToken = "Treasury: invalid token"; string internal insufficientReserves = "Treasury: insufficient reserves"; /* ========== CONSTRUCTOR ========== */ constructor( address _ohm, uint256 _timelock, address _authority ) OlympusAccessControlled(IOlympusAuthority(_authority)) { require(_ohm != address(0), "Zero address: OHM"); OHM = IOHM(_ohm); timelockEnabled = false; initialized = false; blocksNeededForQueue = _timelock; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice allow approved address to deposit an asset for OHM * @param _amount uint256 * @param _token address * @param _profit uint256 * @return send_ uint256 */ function deposit( uint256 _amount, address _token, uint256 _profit ) external override returns (uint256 send_) { if (permissions[STATUS.RESERVETOKEN][_token]) { require(permissions[STATUS.RESERVEDEPOSITOR][msg.sender], notApproved); } else if (permissions[STATUS.LIQUIDITYTOKEN][_token]) { require(permissions[STATUS.LIQUIDITYDEPOSITOR][msg.sender], notApproved); } else { revert(invalidToken); } IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 value = tokenValue(_token, _amount); // mint OHM needed and store amount of rewards for distribution send_ = value.sub(_profit); OHM.mint(msg.sender, send_); totalReserves = totalReserves.add(value); emit Deposit(_token, _amount, value); } /** * @notice allow approved address to burn OHM for reserves * @param _amount uint256 * @param _token address */ function withdraw(uint256 _amount, address _token) external override { require(permissions[STATUS.RESERVETOKEN][_token], notAccepted); // Only reserves can be used for redemptions require(permissions[STATUS.RESERVESPENDER][msg.sender], notApproved); uint256 value = tokenValue(_token, _amount); OHM.burnFrom(msg.sender, value); totalReserves = totalReserves.sub(value); IERC20(_token).safeTransfer(msg.sender, _amount); emit Withdrawal(_token, _amount, value); } /** * @notice allow approved address to withdraw assets * @param _token address * @param _amount uint256 */ function manage(address _token, uint256 _amount) external override { if (permissions[STATUS.LIQUIDITYTOKEN][_token]) { require(permissions[STATUS.LIQUIDITYMANAGER][msg.sender], notApproved); } else { require(permissions[STATUS.RESERVEMANAGER][msg.sender], notApproved); } if ( permissions[STATUS.RESERVETOKEN][_token] || permissions[STATUS.LIQUIDITYTOKEN][_token] ) { uint256 value = tokenValue(_token, _amount); require(value <= excessReserves(), insufficientReserves); totalReserves = totalReserves.sub(value); } IERC20(_token).safeTransfer(msg.sender, _amount); emit Managed(_token, _amount); } /** * @notice mint new OHM using excess reserves * @param _recipient address * @param _amount uint256 */ function mint(address _recipient, uint256 _amount) external override { require(permissions[STATUS.REWARDMANAGER][msg.sender], notApproved); require(_amount <= excessReserves(), insufficientReserves); OHM.mint(_recipient, _amount); emit Minted(msg.sender, _recipient, _amount); } /** * DEBT: The debt functions allow approved addresses to borrow treasury assets * or OHM from the treasury, using sOHM as collateral. This might allow an * sOHM holder to provide OHM liquidity without taking on the opportunity cost * of unstaking, or alter their backing without imposing risk onto the treasury. * Many of these use cases are yet to be defined, but they appear promising. * However, we urge the community to think critically and move slowly upon * proposals to acquire these permissions. */ /** * @notice allow approved address to borrow reserves * @param _amount uint256 * @param _token address */ function incurDebt(uint256 _amount, address _token) external override { uint256 value; if (_token == address(OHM)) { require(permissions[STATUS.OHMDEBTOR][msg.sender], notApproved); value = _amount; } else { require(permissions[STATUS.RESERVEDEBTOR][msg.sender], notApproved); require(permissions[STATUS.RESERVETOKEN][_token], notAccepted); value = tokenValue(_token, _amount); } require(value != 0, invalidToken); sOHM.changeDebt(value, msg.sender, true); require( sOHM.debtBalances(msg.sender) <= debtLimit[msg.sender], "Treasury: exceeds limit" ); totalDebt = totalDebt.add(value); if (_token == address(OHM)) { OHM.mint(msg.sender, value); ohmDebt = ohmDebt.add(value); } else { totalReserves = totalReserves.sub(value); IERC20(_token).safeTransfer(msg.sender, _amount); } emit CreateDebt(msg.sender, _token, _amount, value); } /** * @notice allow approved address to repay borrowed reserves with reserves * @param _amount uint256 * @param _token address */ function repayDebtWithReserve(uint256 _amount, address _token) external override { require(permissions[STATUS.RESERVEDEBTOR][msg.sender], notApproved); require(permissions[STATUS.RESERVETOKEN][_token], notAccepted); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 value = tokenValue(_token, _amount); sOHM.changeDebt(value, msg.sender, false); totalDebt = totalDebt.sub(value); totalReserves = totalReserves.add(value); emit RepayDebt(msg.sender, _token, _amount, value); } /** * @notice allow approved address to repay borrowed reserves with OHM * @param _amount uint256 */ function repayDebtWithOHM(uint256 _amount) external { require( permissions[STATUS.RESERVEDEBTOR][msg.sender] || permissions[STATUS.OHMDEBTOR][msg.sender], notApproved ); OHM.burnFrom(msg.sender, _amount); sOHM.changeDebt(_amount, msg.sender, false); totalDebt = totalDebt.sub(_amount); ohmDebt = ohmDebt.sub(_amount); emit RepayDebt(msg.sender, address(OHM), _amount, _amount); } /* ========== MANAGERIAL FUNCTIONS ========== */ /** * @notice takes inventory of all tracked assets * @notice always consolidate to recognized reserves before audit */ function auditReserves() external onlyGovernor { uint256 reserves; address[] memory reserveToken = registry[STATUS.RESERVETOKEN]; for (uint256 i = 0; i < reserveToken.length; i++) { if (permissions[STATUS.RESERVETOKEN][reserveToken[i]]) { reserves = reserves.add( tokenValue( reserveToken[i], IERC20(reserveToken[i]).balanceOf(address(this)) ) ); } } address[] memory liquidityToken = registry[STATUS.LIQUIDITYTOKEN]; for (uint256 i = 0; i < liquidityToken.length; i++) { if (permissions[STATUS.LIQUIDITYTOKEN][liquidityToken[i]]) { reserves = reserves.add( tokenValue( liquidityToken[i], IERC20(liquidityToken[i]).balanceOf(address(this)) ) ); } } totalReserves = reserves; emit ReservesAudited(reserves); } /** * @notice set max debt for address * @param _address address * @param _limit uint256 */ function setDebtLimit(address _address, uint256 _limit) external onlyGovernor { debtLimit[_address] = _limit; } /** * @notice enable permission from queue * @param _status STATUS * @param _address address * @param _calculator address */ function enable( STATUS _status, address _address, address _calculator ) external onlyGovernor { require(timelockEnabled == false, "Use queueTimelock"); if (_status == STATUS.SOHM) { sOHM = IsOHM(_address); } else { permissions[_status][_address] = true; if (_status == STATUS.LIQUIDITYTOKEN) { bondCalculator[_address] = _calculator; } (bool registered, ) = indexInRegistry(_address, _status); if (!registered) { registry[_status].push(_address); if ( _status == STATUS.LIQUIDITYTOKEN || _status == STATUS.RESERVETOKEN ) { (bool reg, uint256 index) = indexInRegistry(_address, _status); if (reg) { delete registry[_status][index]; } } } } emit Permissioned(_address, _status, true); } /** * @notice disable permission from address * @param _status STATUS * @param _toDisable address */ function disable(STATUS _status, address _toDisable) external { require( msg.sender == authority.governor() || msg.sender == authority.guardian(), "Only governor or guardian" ); permissions[_status][_toDisable] = false; emit Permissioned(_toDisable, _status, false); } /** * @notice check if registry contains address * @return (bool, uint256) */ function indexInRegistry(address _address, STATUS _status) public view returns (bool, uint256) { address[] memory entries = registry[_status]; for (uint256 i = 0; i < entries.length; i++) { if (_address == entries[i]) { return (true, i); } } return (false, 0); } /* ========== TIMELOCKED FUNCTIONS ========== */ // functions are used prior to enabling on-chain governance /** * @notice queue address to receive permission * @param _status STATUS * @param _address address * @param _calculator address */ function queueTimelock( STATUS _status, address _address, address _calculator ) external onlyGovernor { require(_address != address(0)); require(timelockEnabled == true, "Timelock is disabled, use enable"); uint256 timelock = block.number.add(blocksNeededForQueue); if ( _status == STATUS.RESERVEMANAGER || _status == STATUS.LIQUIDITYMANAGER ) { timelock = block.number.add(blocksNeededForQueue.mul(2)); } permissionQueue.push( Queue({ managing: _status, toPermit: _address, calculator: _calculator, timelockEnd: timelock, nullify: false, executed: false }) ); emit PermissionQueued(_status, _address); } /** * @notice enable queued permission * @param _index uint256 */ function execute(uint256 _index) external { require(timelockEnabled == true, "Timelock is disabled, use enable"); Queue memory info = permissionQueue[_index]; require(!info.nullify, "Action has been nullified"); require(!info.executed, "Action has already been executed"); require(block.number >= info.timelockEnd, "Timelock not complete"); if (info.managing == STATUS.SOHM) { // 9 sOHM = IsOHM(info.toPermit); } else { permissions[info.managing][info.toPermit] = true; if (info.managing == STATUS.LIQUIDITYTOKEN) { bondCalculator[info.toPermit] = info.calculator; } (bool registered, ) = indexInRegistry(info.toPermit, info.managing); if (!registered) { registry[info.managing].push(info.toPermit); if (info.managing == STATUS.LIQUIDITYTOKEN) { (bool reg, uint256 index) = indexInRegistry( info.toPermit, STATUS.RESERVETOKEN ); if (reg) { delete registry[STATUS.RESERVETOKEN][index]; } } else if (info.managing == STATUS.RESERVETOKEN) { (bool reg, uint256 index) = indexInRegistry( info.toPermit, STATUS.LIQUIDITYTOKEN ); if (reg) { delete registry[STATUS.LIQUIDITYTOKEN][index]; } } } } permissionQueue[_index].executed = true; emit Permissioned(info.toPermit, info.managing, true); } /** * @notice cancel timelocked action * @param _index uint256 */ function nullify(uint256 _index) external onlyGovernor { permissionQueue[_index].nullify = true; } /** * @notice disables timelocked functions */ function disableTimelock() external onlyGovernor { require(timelockEnabled == true, "timelock already disabled"); if ( onChainGovernanceTimelock != 0 && onChainGovernanceTimelock <= block.number ) { timelockEnabled = false; } else { onChainGovernanceTimelock = block.number.add(blocksNeededForQueue.mul(7)); // 7-day timelock } } /** * @notice enables timelocks after initilization */ function initialize() external onlyGovernor { require(initialized == false, "Already initialized"); timelockEnabled = true; initialized = true; } /* ========== VIEW FUNCTIONS ========== */ /** * @notice returns excess reserves not backing tokens * @return uint */ function excessReserves() public view override returns (uint256) { return totalReserves.sub(OHM.totalSupply().sub(totalDebt)); } /** * @notice returns OHM valuation of asset * @param _token address * @param _amount uint256 * @return value_ uint256 */ function tokenValue(address _token, uint256 _amount) public view override returns (uint256 value_) { value_ = _amount.mul(10**IERC20Metadata(address(OHM)).decimals()).div( 10**IERC20Metadata(_token).decimals() ); if (permissions[STATUS.LIQUIDITYTOKEN][_token]) { value_ = IBondingCalculator(bondCalculator[_token]).valuation( _token, _amount ); } } /** * @notice returns supply metric that cannot be manipulated by debt * @dev use this any time you need to query supply * @return uint256 */ function baseSupply() external view override returns (uint256) { return OHM.totalSupply() - ohmDebt; } }
* @notice returns excess reserves not backing tokens @return uint/
function excessReserves() public view override returns (uint256) { return totalReserves.sub(OHM.totalSupply().sub(totalDebt)); }
14,115,772
[ 1, 6154, 23183, 400, 264, 3324, 486, 15394, 2430, 327, 2254, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 23183, 607, 264, 3324, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 2078, 607, 264, 3324, 18, 1717, 12, 51, 44, 49, 18, 4963, 3088, 1283, 7675, 1717, 12, 4963, 758, 23602, 10019, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: contracts/GRAM.sol // Amended by HashLips, // adapted NFTyGRAMS LLC pragma solidity >=0.7.0 <0.9.0; contract NFTyGRAMS_VD22 is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string internal uriPrefix = "ipfs://Qmee29F38p47DkM5iwRT2bs5jc88okBaktHz4GqJSEm7iq/"; string internal uriSuffix = ".json"; string internal M_uriSuffix = "M.json"; string internal hiddenMetadataUri; uint256 public maxSupply = 1014; uint256 public maxMintAmountPerTx = 1; bool public paused = false; bool public revealed = true; uint256 public maxCharLimit = 120; struct GRAM { string message; } mapping (uint256 => GRAM) private GRAMS; constructor() ERC721("NFTyGRAMS_VD22","GRAM") { setHiddenMetadataUri(""); } modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } function totalSupply() public view returns (uint256) { return supply.current(); } function NeedToUpdateCost(uint256 _supply) internal view returns (uint256 _cost){ if (_supply < 250){ return 13.0; } if (_supply < 500){ return 25.0; } if (_supply < 750){ return 50.0; } if (_supply <= maxSupply){ return 75.0; } } function mint(uint256 _mintAmount, string memory _message) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); require(msg.value >= NeedToUpdateCost(supply.current()) * _mintAmount, "Insufficient funds!"); // check message length bytes memory strBytes = bytes(_message); require(strBytes.length <= maxCharLimit, "Message is too long."); _mintLoop(msg.sender, _mintAmount, _message); } function mintToAddress(uint256 _mintAmount, address _receiver, string memory _message) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); require(msg.value >= NeedToUpdateCost(supply.current()) * _mintAmount, "Insufficient funds!"); // check message length bytes memory strBytes = bytes(_message); require(strBytes.length <= maxCharLimit, "Message is too long."); _mintLoop(_receiver, _mintAmount, _message); } // onlyOwner mint function function _mintForAddress(uint256 _mintAmount, address _receiver, string memory _message) public mintCompliance(_mintAmount) onlyOwner { require(!paused, "The contract is paused!"); // check message length bytes memory strBytes = bytes(_message); require(strBytes.length <= maxCharLimit, "Message is too long."); _mintLoop(_receiver, _mintAmount, _message); } function walletOfOwner(address _owner) public view returns (uint256[] memory){ uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); if (revealed == false) { return hiddenMetadataUri; } GRAM memory currentGRAM = GRAMS[_tokenId]; if(bytes(currentGRAM.message).length > 0) { string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), M_uriSuffix)) : ""; } else { string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } } function setMessage(uint256 _tokenId, string memory _newMessage) public { require(msg.sender == ownerOf(_tokenId), "You are not the owner of this NFT."); bytes memory strBytes = bytes(_newMessage); require(strBytes.length <= maxCharLimit, "Message is too long."); GRAM storage currentGRAM = GRAMS[_tokenId]; if (keccak256(bytes(_newMessage)) != keccak256(bytes(" "))){ // checks string for empty value currentGRAM.message = _newMessage; } else { currentGRAM.message = ""; } } function readMessage(uint256 _tokenId) public view returns (string memory message) { GRAM memory currentGRAM = GRAMS[_tokenId]; return string(currentGRAM.message); } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function withdraw() public onlyOwner { // ============================================================================= 70% (bool m, ) = payable(0x470524c3B9ccf5fa937A599BcAe089724b77F707).call{value: address(this).balance * 70 / 100}(""); require(m); // ============================================================================= 15% (bool j, ) = payable(0x5d2Be86289372fC1EE33e5d5C9B54a60bF501b2F).call{value: address(this).balance * 50 / 100}(""); require(j); // ============================================================================= // This will transfer the remaining contract balance to the owner. // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= 15% (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } function _mintLoop(address _receiver, uint256 _mintAmount, string memory _message) internal { for (uint256 i = 0; i < _mintAmount; i++) { uint256 s = totalSupply(); supply.increment(); // add message GRAM memory newGRAM = GRAM(""); // declares new gram as empty string if (keccak256(bytes(_message)) != keccak256(bytes(" "))){ // checks string for empty value newGRAM.message = _message; } GRAMS[s + 1] = newGRAM; _safeMint(_receiver, supply.current()); } } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
check message length
function mintToAddress(uint256 _mintAmount, address _receiver, string memory _message) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); require(msg.value >= NeedToUpdateCost(supply.current()) * _mintAmount, "Insufficient funds!"); bytes memory strBytes = bytes(_message); require(strBytes.length <= maxCharLimit, "Message is too long."); _mintLoop(_receiver, _mintAmount, _message); }
5,754,397
[ 1, 1893, 883, 769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 312, 474, 774, 1887, 12, 11890, 5034, 389, 81, 474, 6275, 16, 1758, 389, 24454, 16, 533, 3778, 389, 2150, 13, 1071, 8843, 429, 312, 474, 16687, 24899, 81, 474, 6275, 13, 288, 203, 565, 2583, 12, 5, 8774, 3668, 16, 315, 1986, 6835, 353, 17781, 4442, 1769, 203, 565, 2583, 12, 3576, 18, 1132, 1545, 12324, 21267, 8018, 12, 2859, 1283, 18, 2972, 10756, 380, 389, 81, 474, 6275, 16, 315, 5048, 11339, 284, 19156, 4442, 1769, 203, 565, 1731, 3778, 609, 2160, 273, 1731, 24899, 2150, 1769, 203, 565, 2583, 12, 701, 2160, 18, 2469, 1648, 943, 2156, 3039, 16, 315, 1079, 353, 4885, 1525, 1199, 1769, 203, 565, 389, 81, 474, 6452, 24899, 24454, 16, 389, 81, 474, 6275, 16, 389, 2150, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * Tokenomics ____ ____ __ __ | _ \ / __ \\ \ / / /\ | |_) || | | |\ V / / \ | _ < | | | | > < / /\ \ | |_) || |__| |/ . \ / ____ \ |____/ \____//_/ \_\/_/ \_\ * Main Contract (Contract): Boxa – Boxa Coin * Name: Boxa Coin * Symbol: BOXA * Total Supply: 1,000,000,000 * Decimals: 18 * ERC20 token * 6% marketing fee buy/sell * 3% development fee buy/sell * 0% reflection * 3% liquidity buy/sell */ //SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(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; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function getUnlockTime() public view returns (uint256) { return _lockTime; } function getTime() public view returns (uint256) { return block.timestamp; } } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract BoxaToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress = payable(0x7D3c6ba14799E87fA29Ec6B9493aCCa9b517F6E6); // Marketing fee Address address payable public devAddress = payable(0x5662392910d09c8d0AA7853c0cC45E84c3890c61); // development fee Address address payable public rewardAddress = payable(0x3999d2a2cCA6D61473cEA8D705059EfE67835c29); // Reward Address address payable public liquidityAddress = payable(0x3999d2a2cCA6D61473cEA8D705059EfE67835c29); // Liquidity Address, owner address mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1 * 1e9 * 1e18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Boxa Coin"; string private constant _symbol = "BOXA"; uint8 private constant _decimals = 18; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _buyTaxFee = 0; // reflection fee 0% uint256 public _buyLiquidityFee = 3; // liqudity fee in buying case 3% uint256 public _buyRewardFee = 0; // burn fee in buying case 2% uint256 public _buyMarketingFee = 6; // marketing fee in buying case 6% uint256 public _buyDevFee = 3; // development fee in buying case 2% uint256 public _sellTaxFee = 0; // reflection fee 0% uint256 public _sellLiquidityFee = 3; // liqudity fee in buying case 3% uint256 public _sellRewardFee = 0; // burn fee in buying case 2% uint256 public _sellMarketingFee = 6; // marketing fee in buying case 6% uint256 public _sellDevFee = 3; // development fee in buying case 2% uint256 public liquidityActiveBlock; // 0 means liquidity is not active yet uint256 public tradingActiveBlock; // 0 means trading is not active uint256 public deadBlocks; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; mapping (address => bool) public _isExcludedMaxTransactionAmount; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 private _liquidityTokensToSwap; uint256 private _rewardTokens; uint256 private _marketingTokensToSwap; uint256 private _devTokensToSwap; bool private gasLimitActive = true; uint256 private gasPriceLimit = 602 * 1 gwei; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; mapping (address => bool) private _isSniper; uint256 public minimumTokensBeforeSwap; uint256 public maxTransactionAmount; uint256 public maxWallet; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; event RewardLiquidityProviders(uint256 tokenAmount); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event ExcludedMaxTransactionAmount(address indexed account, bool isExcluded); event ManualBurnLP(); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { address newOwner = msg.sender; // update if auto-deploying to a different wallet deadBlocks = 2; maxTransactionAmount = _tTotal * 50 / 10000; // 0.5% max txn minimumTokensBeforeSwap = _tTotal * 5 / 10000; // 0.05% maxWallet = _tTotal * 100 / 10000; // 1% _rOwned[newOwner] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( // Ethereum and Rinkeby 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); _isExcludedFromFee[newOwner] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[liquidityAddress] = true; excludeFromMaxTransaction(newOwner, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(_uniswapV2Router), true); excludeFromMaxTransaction(address(0xdead), true); emit Transfer(address(0), newOwner, _tTotal); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } // once enabled, can never be turned off function enableTrading(uint256 _deadBlocks) external onlyOwner { tradingActive = true; swapAndLiquifyEnabled = true; tradingActiveBlock = block.number; deadBlocks = _deadBlocks; } function isSniper(address account) public view returns (bool) { return _isSniper[account]; } function manageSnipers(address[] calldata addresses, bool status) public onlyOwner { for (uint256 i; i < addresses.length; ++i) { _isSniper[addresses[i]] = status; } } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; excludeFromMaxTransaction(pair, value); if(value){excludeFromReward(pair);} if(!value){includeInReward(pair);} } function setProtectionSettings(bool antiGas) external onlyOwner() { gasLimitActive = antiGas; } function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 300); gasPriceLimit = gas * 1 gwei; } // disable Transfer delay function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } // for one-time airdrop feature after contract launch function airdropToWallets(address[] memory airdropWallets, uint256[] memory amount) external onlyOwner() { require(airdropWallets.length == amount.length, "airdropToWallets:: Arrays must be the same length"); removeAllFee(); buyOrSellSwitch = TRANSFER; for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 airdropAmount = amount[i]; _tokenTransfer(msg.sender, wallet, airdropAmount); } restoreAllFee(); } // remove limits after token is stable - 30-60 minutes function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; transferDelayEnabled = false; return true; } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; emit ExcludedMaxTransactionAmount(updAds, isEx); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); // require(!_isSniper[to], "You have no power here!"); // require(!_isSniper[from], "You have no power here!"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); // only use to prevent sniper buys in the first blocks. if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; // Sell tokens for ETH if ( !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; // If any account belongs to _isExcludedFromFee account then remove the fee if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { // Buy if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } // Sell else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtPercent(uint256 percent) external onlyOwner returns (bool){ require(percent >= 1, "Swap amount cannot be lower than 0.001% total supply."); require(percent <= 50, "Swap amount cannot be higher than 0.5% total supply."); minimumTokensBeforeSwap = _tTotal * percent / 10000; return true; } function updateMaxTxnPercent(uint256 percent) external onlyOwner { require(percent >= 10, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = _tTotal * percent / 10000; } // percent 25 for .25% function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ _transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualBurnLP(); return true; } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); bool success; uint256 totalTokensToSwap = _liquidityTokensToSwap + _rewardTokens + _marketingTokensToSwap + _devTokensToSwap; if(totalTokensToSwap == 0 || contractBalance == 0) {return;} uint256 tokensForLiquidity = (contractBalance * _liquidityTokensToSwap / totalTokensToSwap) / 2; uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity).sub(_rewardTokens); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(_devTokensToSwap).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; // Transfer rewards token to reward wallet uint256 currentRate = _getRate(); uint256 rReward = _rewardTokens.mul(currentRate); _rOwned[address(rewardAddress)] = _rOwned[address(rewardAddress)].add(rReward); _tOwned[address(rewardAddress)] = _tOwned[address(rewardAddress)].add(_rewardTokens); _liquidityTokensToSwap = 0; _rewardTokens = 0; _marketingTokensToSwap = 0; _devTokensToSwap = 0; if(tokensForLiquidity > 0 && ethForLiquidity > 0){ addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingAddress).call{value: address(this).balance.sub(ethForDev)}(""); (success,) = address(devAddress).call{value: ethForDev}(""); } function swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liquidityAddress, block.timestamp ); } function _tokenTransfer( address sender, address recipient, uint256 amount ) private { if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _rewardTokens += tLiquidity * _buyRewardFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; _devTokensToSwap += tLiquidity * _buyDevFee / _liquidityFee; } else if(buyOrSellSwitch == SELL){ _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _rewardTokens += tLiquidity * _sellRewardFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; _devTokensToSwap += tLiquidity * _sellDevFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyRewardFee, uint256 buyMarketingFee, uint256 buyDevFee) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyRewardFee = buyRewardFee; _buyMarketingFee = buyMarketingFee; _buyDevFee = buyDevFee; require(_buyTaxFee + _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee <= 15, "Must keep taxes below 15%"); } function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellRewardFee, uint256 sellMarketingFee, uint256 sellDevFee) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellRewardFee = sellRewardFee; _sellMarketingFee = sellMarketingFee; _sellDevFee = sellDevFee; require(_sellTaxFee + _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee <= 25, "Must keep taxes below 25%"); } function setMarketingAddress(address _marketingAddress) external onlyOwner { marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; } function setDevelopmentAddress(address _devWalletAddress) external onlyOwner { devAddress = payable(_devWalletAddress); _isExcludedFromFee[devAddress] = true; } function setRewardAddress(address _rewardAddress) external onlyOwner { rewardAddress = payable(_rewardAddress); _isExcludedFromFee[rewardAddress] = true; } function setLiquidityAddress(address _liquidityAddress) external onlyOwner { liquidityAddress = payable(_liquidityAddress); _isExcludedFromFee[liquidityAddress] = true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // useful for buybacks or to reclaim any ETH on the contract in a way that helps holders. function buyBackTokens(uint256 ethAmountInWei) external onlyOwner { // generate the uniswap pair path of weth -> eth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmountInWei}( 0, // accept any amount of Token path, address(0xdead), block.timestamp ); } // To receive ETH from uniswapV2Router when swapping receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); } function manualSend(address _recipient) external onlyOwner { uint256 contractETHBalance = address(this).balance; (bool success, ) = _recipient.call{ value: contractETHBalance }(""); require(success, "Address: unable to send value, recipient may have reverted"); } }
Anti-bot and anti-whale mappings and variables store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract BoxaToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1 * 1e9 * 1e18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Boxa Coin"; string private constant _symbol = "BOXA"; uint8 private constant _decimals = 18; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public deadBlocks; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; mapping (address => bool) public _isExcludedMaxTransactionAmount; bool public transferDelayEnabled = true; uint256 private _liquidityTokensToSwap; uint256 private _rewardTokens; uint256 private _marketingTokensToSwap; uint256 private _devTokensToSwap; bool private gasLimitActive = true; uint256 private gasPriceLimit = 602 * 1 gwei; mapping (address => bool) public automatedMarketMakerPairs; mapping (address => bool) private _isSniper; uint256 public minimumTokensBeforeSwap; uint256 public maxTransactionAmount; uint256 public maxWallet; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; event RewardLiquidityProviders(uint256 tokenAmount); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event ExcludedMaxTransactionAmount(address indexed account, bool isExcluded); event ManualBurnLP(); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { deadBlocks = 2; _rOwned[newOwner] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); _isExcludedFromFee[newOwner] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[liquidityAddress] = true; excludeFromMaxTransaction(newOwner, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(_uniswapV2Router), true); excludeFromMaxTransaction(address(0xdead), true); emit Transfer(address(0), newOwner, _tTotal); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } function enableTrading(uint256 _deadBlocks) external onlyOwner { tradingActive = true; swapAndLiquifyEnabled = true; tradingActiveBlock = block.number; deadBlocks = _deadBlocks; } function isSniper(address account) public view returns (bool) { return _isSniper[account]; } function manageSnipers(address[] calldata addresses, bool status) public onlyOwner { for (uint256 i; i < addresses.length; ++i) { _isSniper[addresses[i]] = status; } } function manageSnipers(address[] calldata addresses, bool status) public onlyOwner { for (uint256 i; i < addresses.length; ++i) { _isSniper[addresses[i]] = status; } } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; excludeFromMaxTransaction(pair, value); } if(value){excludeFromReward(pair);} if(!value){includeInReward(pair);} function setProtectionSettings(bool antiGas) external onlyOwner() { gasLimitActive = antiGas; } function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 300); gasPriceLimit = gas * 1 gwei; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } } else { function airdropToWallets(address[] memory airdropWallets, uint256[] memory amount) external onlyOwner() { require(airdropWallets.length == amount.length, "airdropToWallets:: Arrays must be the same length"); removeAllFee(); buyOrSellSwitch = TRANSFER; for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 airdropAmount = amount[i]; _tokenTransfer(msg.sender, wallet, airdropAmount); } restoreAllFee(); } function airdropToWallets(address[] memory airdropWallets, uint256[] memory amount) external onlyOwner() { require(airdropWallets.length == amount.length, "airdropToWallets:: Arrays must be the same length"); removeAllFee(); buyOrSellSwitch = TRANSFER; for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 airdropAmount = amount[i]; _tokenTransfer(msg.sender, wallet, airdropAmount); } restoreAllFee(); } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; transferDelayEnabled = false; return true; } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; emit ExcludedMaxTransactionAmount(updAds, isEx); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } if ( function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ require(tradingActive, "Trading is not enabled yet"); if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Cannot exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && automatedMarketMakerPairs[to] ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function updateSwapTokensAtPercent(uint256 percent) external onlyOwner returns (bool){ require(percent >= 1, "Swap amount cannot be lower than 0.001% total supply."); require(percent <= 50, "Swap amount cannot be higher than 0.5% total supply."); minimumTokensBeforeSwap = _tTotal * percent / 10000; return true; } function updateMaxTxnPercent(uint256 percent) external onlyOwner { require(percent >= 10, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = _tTotal * percent / 10000; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ _transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualBurnLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ _transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualBurnLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); bool success; uint256 totalTokensToSwap = _liquidityTokensToSwap + _rewardTokens + _marketingTokensToSwap + _devTokensToSwap; uint256 tokensForLiquidity = (contractBalance * _liquidityTokensToSwap / totalTokensToSwap) / 2; uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity).sub(_rewardTokens); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(_devTokensToSwap).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; uint256 currentRate = _getRate(); uint256 rReward = _rewardTokens.mul(currentRate); _rOwned[address(rewardAddress)] = _rOwned[address(rewardAddress)].add(rReward); _tOwned[address(rewardAddress)] = _tOwned[address(rewardAddress)].add(_rewardTokens); _liquidityTokensToSwap = 0; _rewardTokens = 0; _marketingTokensToSwap = 0; _devTokensToSwap = 0; if(tokensForLiquidity > 0 && ethForLiquidity > 0){ addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(totalTokensToSwap == 0 || contractBalance == 0) {return;} function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); bool success; uint256 totalTokensToSwap = _liquidityTokensToSwap + _rewardTokens + _marketingTokensToSwap + _devTokensToSwap; uint256 tokensForLiquidity = (contractBalance * _liquidityTokensToSwap / totalTokensToSwap) / 2; uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity).sub(_rewardTokens); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(_devTokensToSwap).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; uint256 currentRate = _getRate(); uint256 rReward = _rewardTokens.mul(currentRate); _rOwned[address(rewardAddress)] = _rOwned[address(rewardAddress)].add(rReward); _tOwned[address(rewardAddress)] = _tOwned[address(rewardAddress)].add(_rewardTokens); _liquidityTokensToSwap = 0; _rewardTokens = 0; _marketingTokensToSwap = 0; _devTokensToSwap = 0; if(tokensForLiquidity > 0 && ethForLiquidity > 0){ addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingAddress).call{value: address(this).balance.sub(ethForDev)}(""); (success,) = address(devAddress).call{value: ethForDev}(""); function swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, liquidityAddress, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function _tokenTransfer( address sender, address recipient, uint256 amount ) private { if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } } function _tokenTransfer( address sender, address recipient, uint256 amount ) private { if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } } } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _rewardTokens += tLiquidity * _buyRewardFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; _devTokensToSwap += tLiquidity * _buyDevFee / _liquidityFee; _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _rewardTokens += tLiquidity * _sellRewardFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; _devTokensToSwap += tLiquidity * _sellDevFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _rewardTokens += tLiquidity * _buyRewardFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; _devTokensToSwap += tLiquidity * _buyDevFee / _liquidityFee; _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _rewardTokens += tLiquidity * _sellRewardFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; _devTokensToSwap += tLiquidity * _sellDevFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } } else if(buyOrSellSwitch == SELL){ function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyRewardFee, uint256 buyMarketingFee, uint256 buyDevFee) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyRewardFee = buyRewardFee; _buyMarketingFee = buyMarketingFee; _buyDevFee = buyDevFee; require(_buyTaxFee + _buyLiquidityFee + _buyRewardFee + _buyMarketingFee + _buyDevFee <= 15, "Must keep taxes below 15%"); } function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellRewardFee, uint256 sellMarketingFee, uint256 sellDevFee) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellRewardFee = sellRewardFee; _sellMarketingFee = sellMarketingFee; _sellDevFee = sellDevFee; require(_sellTaxFee + _sellLiquidityFee + _sellRewardFee + _sellMarketingFee + _sellDevFee <= 25, "Must keep taxes below 25%"); } function setMarketingAddress(address _marketingAddress) external onlyOwner { marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; } function setDevelopmentAddress(address _devWalletAddress) external onlyOwner { devAddress = payable(_devWalletAddress); _isExcludedFromFee[devAddress] = true; } function setRewardAddress(address _rewardAddress) external onlyOwner { rewardAddress = payable(_rewardAddress); _isExcludedFromFee[rewardAddress] = true; } function setLiquidityAddress(address _liquidityAddress) external onlyOwner { liquidityAddress = payable(_liquidityAddress); _isExcludedFromFee[liquidityAddress] = true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function buyBackTokens(uint256 ethAmountInWei) external onlyOwner { address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); path, address(0xdead), block.timestamp ); } uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmountInWei}( receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); } function manualSend(address _recipient) external onlyOwner { uint256 contractETHBalance = address(this).balance; require(success, "Address: unable to send value, recipient may have reverted"); } (bool success, ) = _recipient.call{ value: contractETHBalance }(""); }
5,993,284
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8549, 69, 1345, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 203, 565, 1758, 8526, 3238, 389, 24602, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 404, 380, 404, 73, 29, 380, 404, 73, 2643, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 203, 565, 533, 3238, 5381, 389, 529, 273, 315, 3514, 69, 28932, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 315, 16876, 37, 14432, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 6549, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 10937, 61, 273, 404, 31, 203, 565, 2254, 5034, 3238, 5381, 20853, 48, 273, 576, 31, 203, 565, 2254, 5034, 3238, 5381, 4235, 17598, 273, 890, 31, 2 ]
./partial_match/1/0xF531F46686c392c32B1fbA13c0c79eb5b5390e36/sources/FeatherFarm.sol
only Works if tokens are on the token contract. They need to be sent here 1st. (by the team Treasury)
_burn(address(this), amount);
3,663,430
[ 1, 3700, 4147, 87, 309, 2430, 854, 603, 326, 1147, 6835, 18, 16448, 1608, 358, 506, 3271, 2674, 404, 334, 18, 261, 1637, 326, 5927, 399, 266, 345, 22498, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 70, 321, 12, 2867, 12, 2211, 3631, 3844, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-03-30 */ /** ▄▄▄▄▄ ██ █▄▄▄▄ ▄█▄ ████▄ █ ▄▄ ▄ █ ██ ▄▀ ▄ ▄▄▄▄▄ █ ▀▄ █ █ █ ▄▀ █▀ ▀▄ █ █ █ █ █ █ █ █ ▄▀ █ █ ▀▄ ▄ ▀▀▀▀▄ █▄▄█ █▀▀▌ █ ▀ █ █ █▀▀▀ ██▀▀█ █▄▄█ █ ▀▄ █ █ ▄ ▀▀▀▀▄ ▀▄▄▄▄▀ █ █ █ █ █▄ ▄▀ ▀████ █ █ █ █ █ █ █ █ █ ▀▄▄▄▄▀ █ █ ▀███▀ █ █ █ ███ █▄ ▄█ █ ▀ ▀ ▀ █ ▀▀▀ ▀ ▀ */ // File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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); } } } } // File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/libraries/Events.sol pragma solidity ^0.8.0; /** * @title A collection of Events * @notice This library defines all of the Events that the Sarcophagus system * emits */ library Events { event Creation(address sarcophagusContract); event RegisterArchaeologist( address indexed archaeologist, bytes currentPublicKey, string endpoint, address paymentAddress, uint256 feePerByte, uint256 minimumBounty, uint256 minimumDiggingFee, uint256 maximumResurrectionTime, uint256 bond ); event UpdateArchaeologist( address indexed archaeologist, string endpoint, address paymentAddress, uint256 feePerByte, uint256 minimumBounty, uint256 minimumDiggingFee, uint256 maximumResurrectionTime, uint256 addedBond ); event UpdateArchaeologistPublicKey( address indexed archaeologist, bytes currentPublicKey ); event WithdrawalFreeBond( address indexed archaeologist, uint256 withdrawnBond ); event CreateSarcophagus( bytes32 indexed identifier, address indexed archaeologist, bytes archaeologistPublicKey, address embalmer, string name, uint256 resurrectionTime, uint256 resurrectionWindow, uint256 storageFee, uint256 diggingFee, uint256 bounty, bytes recipientPublicKey, uint256 cursedBond ); event UpdateSarcophagus(bytes32 indexed identifier, string assetId); event CancelSarcophagus(bytes32 indexed identifier); event RewrapSarcophagus( string assetId, bytes32 indexed identifier, uint256 resurrectionTime, uint256 resurrectionWindow, uint256 diggingFee, uint256 bounty, uint256 cursedBond ); event UnwrapSarcophagus( string assetId, bytes32 indexed identifier, bytes32 privatekey ); event AccuseArchaeologist( bytes32 indexed identifier, address indexed accuser, uint256 accuserBondReward, uint256 embalmerBondReward ); event BurySarcophagus(bytes32 indexed identifier); event CleanUpSarcophagus( bytes32 indexed identifier, address indexed cleaner, uint256 cleanerBondReward, uint256 embalmerBondReward ); } // File: contracts/libraries/Types.sol pragma solidity ^0.8.0; /** * @title A collection of defined structs * @notice This library defines the various data models that the Sarcophagus * system uses */ library Types { struct Archaeologist { bool exists; bytes currentPublicKey; string endpoint; address paymentAddress; uint256 feePerByte; uint256 minimumBounty; uint256 minimumDiggingFee; uint256 maximumResurrectionTime; uint256 freeBond; uint256 cursedBond; } enum SarcophagusStates {DoesNotExist, Exists, Done} struct Sarcophagus { SarcophagusStates state; address archaeologist; bytes archaeologistPublicKey; address embalmer; string name; uint256 resurrectionTime; uint256 resurrectionWindow; string assetId; bytes recipientPublicKey; uint256 storageFee; uint256 diggingFee; uint256 bounty; uint256 currentCursedBond; bytes32 privateKey; } } // File: contracts/libraries/Datas.sol pragma solidity ^0.8.0; /** * @title A library implementing data structures for the Sarcophagus system * @notice This library defines a Data struct, which defines all of the state * that the Sarcophagus system needs to operate. It's expected that a single * instance of this state will exist. */ library Datas { struct Data { // archaeologists address[] archaeologistAddresses; mapping(address => Types.Archaeologist) archaeologists; // archaeologist stats mapping(address => bytes32[]) archaeologistSuccesses; mapping(address => bytes32[]) archaeologistCancels; mapping(address => bytes32[]) archaeologistAccusals; mapping(address => bytes32[]) archaeologistCleanups; // archaeologist key control mapping(bytes => bool) archaeologistUsedKeys; // sarcophaguses bytes32[] sarcophagusIdentifiers; mapping(bytes32 => Types.Sarcophagus) sarcophaguses; // sarcophagus ownerships mapping(address => bytes32[]) embalmerSarcophaguses; mapping(address => bytes32[]) archaeologistSarcophaguses; mapping(address => bytes32[]) recipientSarcophaguses; } } // File: contracts/libraries/Utils.sol pragma solidity ^0.8.0; /** * @title Utility functions used within the Sarcophagus system * @notice This library implements various functions that are used throughout * Sarcophagus, mainly to DRY up the codebase * @dev these functions are all stateless, public, pure/view */ library Utils { /** * @notice Reverts if the public key length is not exactly 64 bytes long * @param publicKey the key to check length of */ function publicKeyLength(bytes memory publicKey) public pure { require(publicKey.length == 64, "public key must be 64 bytes"); } /** * @notice Reverts if the hash of singleHash does not equal doubleHash * @param doubleHash the hash to compare hash of singleHash to * @param singleHash the value to hash and compare against doubleHash */ function hashCheck(bytes32 doubleHash, bytes memory singleHash) public pure { require(doubleHash == keccak256(singleHash), "hashes do not match"); } /** * @notice Reverts if the input string is not empty * @param assetId the string to check */ function confirmAssetIdNotSet(string memory assetId) public pure { require(bytes(assetId).length == 0, "assetId has already been set"); } /** * @notice Reverts if existing assetId is not empty, or if new assetId is * @param existingAssetId the orignal assetId to check, make sure is empty * @param newAssetId the new assetId, which must not be empty */ function assetIdsCheck( string memory existingAssetId, string memory newAssetId ) public pure { // verify that the existingAssetId is currently empty confirmAssetIdNotSet(existingAssetId); require(bytes(newAssetId).length > 0, "assetId must not have 0 length"); } /** * @notice Reverts if the given data and signature did not come from the * given address * @param data the payload which has been signed * @param v signature element * @param r signature element * @param s signature element * @param account address to confirm data and signature came from */ function signatureCheck( bytes memory data, uint8 v, bytes32 r, bytes32 s, address account ) public pure { // generate the address for a given data and signature address hopefulAddress = ecrecover(keccak256(data), v, r, s); require( hopefulAddress == account, "signature did not come from correct account" ); } /** * @notice Reverts if the given resurrection time is not in the future * @param resurrectionTime the time to check against block.timestamp */ function resurrectionInFuture(uint256 resurrectionTime) public view { require( resurrectionTime > block.timestamp, "resurrection time must be in the future" ); } /** * @notice Calculates the grace period that an archaeologist has after a * sarcophagus has reached its resurrection time * @param resurrectionTime the resurrection timestamp of a sarcophagus * @return the grace period * @dev The grace period is dependent on how far out the resurrection time * is. The longer out the resurrection time, the longer the grace period. * There is a minimum grace period of 30 minutes, otherwise, it's * calculated as 1% of the time between now and resurrection time. */ function getGracePeriod(uint256 resurrectionTime) public view returns (uint256) { // set a minimum window of 30 minutes uint16 minimumResurrectionWindow = 30 minutes; // calculate 1% of the relative time between now and the resurrection // time uint256 gracePeriod = (resurrectionTime - block.timestamp) / 100; // if our calculated grace period is less than the minimum time, we'll // use the minimum time instead if (gracePeriod < minimumResurrectionWindow) { gracePeriod = minimumResurrectionWindow; } // return that grace period return gracePeriod; } /** * @notice Reverts if we're not within the resurrection window (on either * side) * @param resurrectionTime the resurrection time of the sarcophagus * (absolute, i.e. a date time stamp) * @param resurrectionWindow the resurrection window of the sarcophagus * (relative, i.e. "30 minutes") */ function unwrapTime(uint256 resurrectionTime, uint256 resurrectionWindow) public view { // revert if too early require( resurrectionTime <= block.timestamp, "it's not time to unwrap the sarcophagus" ); // revert if too late require( resurrectionTime + resurrectionWindow >= block.timestamp, "the resurrection window has expired" ); } /** * @notice Reverts if msg.sender is not equal to passed-in address * @param account the account to verify is msg.sender */ function sarcophagusUpdater(address account) public view { require( account == msg.sender, "sarcophagus cannot be updated by account" ); } /** * @notice Reverts if the input resurrection time, digging fee, or bounty * don't fit within the other given maximum and minimum values * @param resurrectionTime the resurrection time to check * @param diggingFee the digging fee to check * @param bounty the bounty to check * @param maximumResurrectionTime the maximum resurrection time to check * against, in relative terms (i.e. "1 year" is 31536000 (seconds)) * @param minimumDiggingFee the minimum digging fee to check against * @param minimumBounty the minimum bounty to check against */ function withinArchaeologistLimits( uint256 resurrectionTime, uint256 diggingFee, uint256 bounty, uint256 maximumResurrectionTime, uint256 minimumDiggingFee, uint256 minimumBounty ) public view { // revert if the given resurrection time is too far in the future require( resurrectionTime <= block.timestamp + maximumResurrectionTime, "resurrection time too far in the future" ); // revert if the given digging fee is too low require(diggingFee >= minimumDiggingFee, "digging fee is too low"); // revert if the given bounty is too low require(bounty >= minimumBounty, "bounty is too low"); } } // File: contracts/libraries/Archaeologists.sol pragma solidity ^0.8.0; /** * @title A library implementing Archaeologist-specific logic in the * Sarcophagus system * @notice This library includes public functions for manipulating * archaeologists in the Sarcophagus system */ library Archaeologists { /** * @notice Checks that an archaeologist exists, or doesn't exist, and * and reverts if necessary * @param data the system's data struct instance * @param account the archaeologist address to check existence of * @param exists bool which flips whether function reverts if archaeologist * exists or not */ function archaeologistExists( Datas.Data storage data, address account, bool exists ) public view { // set the error message string memory err = "archaeologist has not been registered yet"; if (!exists) err = "archaeologist has already been registered"; // revert if necessary require(data.archaeologists[account].exists == exists, err); } /** * @notice Increases internal data structure which tracks free bond per * archaeologist * @param data the system's data struct instance * @param archAddress the archaeologist's address to operate on * @param amount the amount to increase free bond by */ function increaseFreeBond( Datas.Data storage data, address archAddress, uint256 amount ) private { // load up the archaeologist Types.Archaeologist storage arch = data.archaeologists[archAddress]; // increase the freeBond variable by amount arch.freeBond = arch.freeBond + amount; } /** * @notice Decreases internal data structure which tracks free bond per * archaeologist * @param data the system's data struct instance * @param archAddress the archaeologist's address to operate on * @param amount the amount to decrease free bond by */ function decreaseFreeBond( Datas.Data storage data, address archAddress, uint256 amount ) private { // load up the archaeologist Types.Archaeologist storage arch = data.archaeologists[archAddress]; // decrease the free bond variable by amount, reverting if necessary require( arch.freeBond >= amount, "archaeologist does not have enough free bond" ); arch.freeBond = arch.freeBond - amount; } /** * @notice Increases internal data structure which tracks cursed bond per * archaeologist * @param data the system's data struct instance * @param archAddress the archaeologist's address to operate on * @param amount the amount to increase cursed bond by */ function increaseCursedBond( Datas.Data storage data, address archAddress, uint256 amount ) private { // load up the archaeologist Types.Archaeologist storage arch = data.archaeologists[archAddress]; // increase the freeBond variable by amount arch.cursedBond = arch.cursedBond + amount; } /** * @notice Decreases internal data structure which tracks cursed bond per * archaeologist * @param data the system's data struct instance * @param archAddress the archaeologist's address to operate on * @param amount the amount to decrease cursed bond by */ function decreaseCursedBond( Datas.Data storage data, address archAddress, uint256 amount ) public { // load up the archaeologist Types.Archaeologist storage arch = data.archaeologists[archAddress]; // decrease the free bond variable by amount arch.cursedBond = arch.cursedBond - amount; } /** * @notice Given an archaeologist and amount, decrease free bond and * increase cursed bond * @param data the system's data struct instance * @param archAddress the archaeologist's address to operate on * @param amount the amount to decrease free bond and increase cursed bond */ function lockUpBond( Datas.Data storage data, address archAddress, uint256 amount ) public { decreaseFreeBond(data, archAddress, amount); increaseCursedBond(data, archAddress, amount); } /** * @notice Given an archaeologist and amount, increase free bond and * decrease cursed bond * @param data the system's data struct instance * @param archAddress the archaeologist's address to operate on * @param amount the amount to increase free bond and decrease cursed bond */ function freeUpBond( Datas.Data storage data, address archAddress, uint256 amount ) public { increaseFreeBond(data, archAddress, amount); decreaseCursedBond(data, archAddress, amount); } /** * @notice Calculates and returns the curse for any sarcophagus * @param diggingFee the digging fee of a sarcophagus * @param bounty the bounty of a sarcophagus * @return amount of the curse * @dev Current implementation simply adds the two inputs together. Future * strategies should use historical data to build a curve to change this * amount over time. */ function getCursedBond(uint256 diggingFee, uint256 bounty) public pure returns (uint256) { // TODO: implment a better algorithm, using some concept of past state return diggingFee + bounty; } /** * @notice Registers a new archaeologist in the system * @param data the system's data struct instance * @param currentPublicKey the public key to be used in the first * sarcophagus * @param endpoint where to contact this archaeologist on the internet * @param paymentAddress all collected payments for the archaeologist will * be sent here * @param feePerByte amount of SARCO tokens charged per byte of storage * being sent to Arweave * @param minimumBounty the minimum bounty for a sarcophagus that the * archaeologist will accept * @param minimumDiggingFee the minimum digging fee for a sarcophagus that * the archaeologist will accept * @param maximumResurrectionTime the maximum resurrection time for a * sarcophagus that the archaeologist will accept, in relative terms (i.e. * "1 year" is 31536000 (seconds)) * @param freeBond the amount of SARCO bond that the archaeologist wants * to start with * @param sarcoToken the SARCO token used for payment handling * @return index of the new archaeologist */ function registerArchaeologist( Datas.Data storage data, bytes memory currentPublicKey, string memory endpoint, address paymentAddress, uint256 feePerByte, uint256 minimumBounty, uint256 minimumDiggingFee, uint256 maximumResurrectionTime, uint256 freeBond, IERC20 sarcoToken ) public returns (uint256) { // verify that the archaeologist does not already exist archaeologistExists(data, msg.sender, false); // verify that the public key length is accurate Utils.publicKeyLength(currentPublicKey); // transfer SARCO tokens from the archaeologist to this contract, to be // used as their free bond. can be 0, which indicates that the // archaeologist is not eligible for any new jobs if (freeBond > 0) { sarcoToken.transferFrom(msg.sender, address(this), freeBond); } // create a new archaeologist Types.Archaeologist memory newArch = Types.Archaeologist({ exists: true, currentPublicKey: currentPublicKey, endpoint: endpoint, paymentAddress: paymentAddress, feePerByte: feePerByte, minimumBounty: minimumBounty, minimumDiggingFee: minimumDiggingFee, maximumResurrectionTime: maximumResurrectionTime, freeBond: freeBond, cursedBond: 0 }); // save the new archaeologist into relevant data structures data.archaeologists[msg.sender] = newArch; data.archaeologistAddresses.push(msg.sender); // emit an event emit Events.RegisterArchaeologist( msg.sender, newArch.currentPublicKey, newArch.endpoint, newArch.paymentAddress, newArch.feePerByte, newArch.minimumBounty, newArch.minimumDiggingFee, newArch.maximumResurrectionTime, newArch.freeBond ); // return index of the new archaeologist return data.archaeologistAddresses.length - 1; } /** * @notice An archaeologist may update their profile * @param data the system's data struct instance * @param endpoint where to contact this archaeologist on the internet * @param newPublicKey the public key to be used in the next * sarcophagus * @param paymentAddress all collected payments for the archaeologist will * be sent here * @param feePerByte amount of SARCO tokens charged per byte of storage * being sent to Arweave * @param minimumBounty the minimum bounty for a sarcophagus that the * archaeologist will accept * @param minimumDiggingFee the minimum digging fee for a sarcophagus that * the archaeologist will accept * @param maximumResurrectionTime the maximum resurrection time for a * sarcophagus that the archaeologist will accept, in relative terms (i.e. * "1 year" is 31536000 (seconds)) * @param freeBond the amount of SARCO bond that the archaeologist wants * to add to their profile * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the update was successful */ function updateArchaeologist( Datas.Data storage data, bytes memory newPublicKey, string memory endpoint, address paymentAddress, uint256 feePerByte, uint256 minimumBounty, uint256 minimumDiggingFee, uint256 maximumResurrectionTime, uint256 freeBond, IERC20 sarcoToken ) public returns (bool) { // verify that the archaeologist exists, and is the sender of this // transaction archaeologistExists(data, msg.sender, true); // load up the archaeologist Types.Archaeologist storage arch = data.archaeologists[msg.sender]; // if archaeologist is updating their active public key, emit an event if (keccak256(arch.currentPublicKey) != keccak256(newPublicKey)) { emit Events.UpdateArchaeologistPublicKey(msg.sender, newPublicKey); arch.currentPublicKey = newPublicKey; } // update the rest of the archaeologist profile arch.endpoint = endpoint; arch.paymentAddress = paymentAddress; arch.feePerByte = feePerByte; arch.minimumBounty = minimumBounty; arch.minimumDiggingFee = minimumDiggingFee; arch.maximumResurrectionTime = maximumResurrectionTime; // the freeBond variable acts as an incrementer, so only if it's above // zero will we update their profile variable and transfer the tokens if (freeBond > 0) { increaseFreeBond(data, msg.sender, freeBond); sarcoToken.transferFrom(msg.sender, address(this), freeBond); } // emit an event emit Events.UpdateArchaeologist( msg.sender, arch.endpoint, arch.paymentAddress, arch.feePerByte, arch.minimumBounty, arch.minimumDiggingFee, arch.maximumResurrectionTime, freeBond ); // return true return true; } /** * @notice Archaeologist can withdraw any of their free bond * @param data the system's data struct instance * @param amount the amount of the archaeologist's free bond that they're * withdrawing * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the withdrawal was successful */ function withdrawBond( Datas.Data storage data, uint256 amount, IERC20 sarcoToken ) public returns (bool) { // verify that the archaeologist exists, and is the sender of this // transaction archaeologistExists(data, msg.sender, true); // move free bond out of the archaeologist decreaseFreeBond(data, msg.sender, amount); // transfer the freed SARCOs back to the archaeologist sarcoToken.transfer(msg.sender, amount); // emit event emit Events.WithdrawalFreeBond(msg.sender, amount); // return true return true; } } // File: contracts/libraries/PrivateKeys.sol pragma solidity ^0.8.0; /** * @title Private key verification * @notice Implements a private key -> public key checking function * @dev modified from https://github.com/1Address/ecsol, removes extra code * which isn't necessary for our Sarcophagus implementation */ library PrivateKeys { uint256 public constant gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 public constant gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; // // Based on the original idea of Vitalik Buterin: // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 // function ecmulVerify( uint256 x1, uint256 y1, bytes32 scalar, bytes memory pubKey ) private pure returns (bool) { uint256 m = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; address signer = ecrecover( 0, y1 % 2 != 0 ? 28 : 27, bytes32(x1), bytes32(mulmod(uint256(scalar), x1, m)) ); address xyAddress = address( uint160( uint256(keccak256(pubKey)) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ) ); return xyAddress == signer; } /** * @notice Given a private key and a public key, determines if that public * key was derived from the private key * @param privKey an secp256k1 private key * @param pubKey an secp256k1 public key * @return bool indicating whether the public key is derived from the * private key */ function keyVerification(bytes32 privKey, bytes memory pubKey) public pure returns (bool) { return ecmulVerify(gx, gy, privKey, pubKey); } } // File: contracts/libraries/Sarcophaguses.sol pragma solidity ^0.8.0; /** * @title A library implementing Sarcophagus-specific logic in the * Sarcophagus system * @notice This library includes public functions for manipulating * sarcophagi in the Sarcophagus system */ library Sarcophaguses { /** * @notice Reverts if the given sarcState does not equal the comparison * state * @param sarcState the state of a sarcophagus * @param state the state to compare to */ function sarcophagusState( Types.SarcophagusStates sarcState, Types.SarcophagusStates state ) internal pure { // set the error message string memory error = "sarcophagus already exists"; if (state == Types.SarcophagusStates.Exists) error = "sarcophagus does not exist or is not active"; // revert if states are not equal require(sarcState == state, error); } /** * @notice Takes a sarcophagus's cursed bond, splits it in half, and sends * to the transaction caller and embalmer * @param data the system's data struct instance * @param paymentAddress payment address for the transaction caller * @param sarc the sarcophagus to operate on * @param sarcoToken the SARCO token used for payment handling * @return halfToSender the amount of SARCO token going to transaction * sender * @return halfToEmbalmer the amount of SARCO token going to embalmer */ function splitSend( Datas.Data storage data, address paymentAddress, Types.Sarcophagus storage sarc, IERC20 sarcoToken ) private returns (uint256, uint256) { // split the sarcophagus's cursed bond into two halves, taking into // account solidity math uint256 halfToEmbalmer = sarc.currentCursedBond / 2; uint256 halfToSender = sarc.currentCursedBond - halfToEmbalmer; // transfer the cursed half, plus bounty, plus digging fee to the // embalmer sarcoToken.transfer( sarc.embalmer, sarc.bounty + sarc.diggingFee + halfToEmbalmer ); // transfer the other half of the cursed bond to the transaction caller sarcoToken.transfer(paymentAddress, halfToSender); // update (decrease) the archaeologist's cursed bond, because this // sarcophagus is over Archaeologists.decreaseCursedBond( data, sarc.archaeologist, sarc.currentCursedBond ); // return data return (halfToSender, halfToEmbalmer); } /** * @notice Embalmer creates the skeleton for a new sarcopahgus * @param data the system's data struct instance * @param name the name of the sarcophagus * @param archaeologist the address of a registered archaeologist to * assign this sarcophagus to * @param resurrectionTime the resurrection time of the sarcophagus * @param storageFee the storage fee that the archaeologist will receive, * for saving this sarcophagus on Arweave * @param diggingFee the digging fee that the archaeologist will receive at * the first rewrap * @param bounty the bounty that the archaeologist will receive when the * sarcophagus is unwrapped * @param identifier the identifier of the sarcophagus, which is the hash * of the hash of the inner encrypted layer of the sarcophagus * @param recipientPublicKey the public key of the recipient * @param sarcoToken the SARCO token used for payment handling * @return index of the new sarcophagus */ function createSarcophagus( Datas.Data storage data, string memory name, address archaeologist, uint256 resurrectionTime, uint256 storageFee, uint256 diggingFee, uint256 bounty, bytes32 identifier, bytes memory recipientPublicKey, IERC20 sarcoToken ) public returns (uint256) { // confirm that the archaeologist exists Archaeologists.archaeologistExists(data, archaeologist, true); // confirm that the public key length is correct Utils.publicKeyLength(recipientPublicKey); // confirm that this exact sarcophagus does not yet exist sarcophagusState( data.sarcophaguses[identifier].state, Types.SarcophagusStates.DoesNotExist ); // confirm that the resurrection time is in the future Utils.resurrectionInFuture(resurrectionTime); // load the archaeologist Types.Archaeologist memory arch = data.archaeologists[archaeologist]; // check that the new sarcophagus parameters fit within the selected // archaeologist's parameters Utils.withinArchaeologistLimits( resurrectionTime, diggingFee, bounty, arch.maximumResurrectionTime, arch.minimumDiggingFee, arch.minimumBounty ); // calculate the amount of archaeologist's bond to lock up uint256 cursedBondAmount = Archaeologists.getCursedBond(diggingFee, bounty); // lock up that bond Archaeologists.lockUpBond(data, archaeologist, cursedBondAmount); // create a new sarcophagus Types.Sarcophagus memory sarc = Types.Sarcophagus({ state: Types.SarcophagusStates.Exists, archaeologist: archaeologist, archaeologistPublicKey: arch.currentPublicKey, embalmer: msg.sender, name: name, resurrectionTime: resurrectionTime, resurrectionWindow: Utils.getGracePeriod(resurrectionTime), assetId: "", recipientPublicKey: recipientPublicKey, storageFee: storageFee, diggingFee: diggingFee, bounty: bounty, currentCursedBond: cursedBondAmount, privateKey: 0 }); // derive the recipient's address from their public key address recipientAddress = address(uint160(uint256(keccak256(recipientPublicKey)))); // save the sarcophagus into necessary data structures data.sarcophaguses[identifier] = sarc; data.sarcophagusIdentifiers.push(identifier); data.embalmerSarcophaguses[msg.sender].push(identifier); data.archaeologistSarcophaguses[archaeologist].push(identifier); data.recipientSarcophaguses[recipientAddress].push(identifier); // transfer digging fee + bounty + storage fee from embalmer to this // contract sarcoToken.transferFrom( msg.sender, address(this), diggingFee + bounty + storageFee ); // emit event with all the data emit Events.CreateSarcophagus( identifier, sarc.archaeologist, sarc.archaeologistPublicKey, sarc.embalmer, sarc.name, sarc.resurrectionTime, sarc.resurrectionWindow, sarc.storageFee, sarc.diggingFee, sarc.bounty, sarc.recipientPublicKey, sarc.currentCursedBond ); // return index of the new sarcophagus return data.sarcophagusIdentifiers.length - 1; } /** * @notice Embalmer updates a sarcophagus given it's identifier, after * the archaeologist has uploaded the encrypted payload onto Arweave * @param data the system's data struct instance * @param newPublicKey the archaeologist's new public key, to use for * encrypting the next sarcophagus that they're assigned to * @param identifier the identifier of the sarcophagus * @param assetId the identifier of the encrypted asset on Arweave * @param v signature element * @param r signature element * @param s signature element * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the update was successful */ function updateSarcophagus( Datas.Data storage data, bytes memory newPublicKey, bytes32 identifier, string memory assetId, uint8 v, bytes32 r, bytes32 s, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that the embalmer is making this transaction Utils.sarcophagusUpdater(sarc.embalmer); // verify that the sarcophagus does not currently have an assetId, and // that we are setting an actual assetId Utils.assetIdsCheck(sarc.assetId, assetId); // verify that the archaeologist's new public key, and the assetId, // actually came from the archaeologist and were not tampered Utils.signatureCheck( abi.encodePacked(newPublicKey, assetId), v, r, s, sarc.archaeologist ); // revert if the new public key coming from the archaeologist has // already been used require( !data.archaeologistUsedKeys[sarc.archaeologistPublicKey], "public key already used" ); // make sure that the new public key can't be used again in the future data.archaeologistUsedKeys[sarc.archaeologistPublicKey] = true; // set the assetId on the sarcophagus sarc.assetId = assetId; // load up the archaeologist Types.Archaeologist storage arch = data.archaeologists[sarc.archaeologist]; // set the new public key on the archaeologist arch.currentPublicKey = newPublicKey; // transfer the storage fee to the archaeologist sarcoToken.transfer(arch.paymentAddress, sarc.storageFee); sarc.storageFee = 0; // emit some events emit Events.UpdateSarcophagus(identifier, assetId); emit Events.UpdateArchaeologistPublicKey( sarc.archaeologist, arch.currentPublicKey ); // return true return true; } /** * @notice An embalmer may cancel a sarcophagus if it hasn't been * completely created * @param data the system's data struct instance * @param identifier the identifier of the sarcophagus * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the cancel was successful */ function cancelSarcophagus( Datas.Data storage data, bytes32 identifier, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that the asset id has not yet been set Utils.confirmAssetIdNotSet(sarc.assetId); // verify that the embalmer is making this transaction Utils.sarcophagusUpdater(sarc.embalmer); // transfer the bounty and storage fee back to the embalmer sarcoToken.transfer(sarc.embalmer, sarc.bounty + sarc.storageFee); // load the archaeologist Types.Archaeologist memory arch = data.archaeologists[sarc.archaeologist]; // transfer the digging fee over to the archaeologist sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee); // free up the cursed bond on the archaeologist, because this // sarcophagus is over Archaeologists.freeUpBond( data, sarc.archaeologist, sarc.currentCursedBond ); // set the sarcophagus state to Done sarc.state = Types.SarcophagusStates.Done; // save the fact that this sarcophagus has been cancelled, against the // archaeologist data.archaeologistCancels[sarc.archaeologist].push(identifier); // emit an event emit Events.CancelSarcophagus(identifier); // return true return true; } /** * @notice Embalmer can extend the resurrection time of the sarcophagus, * as long as the previous resurrection time is in the future * @param data the system's data struct instance * @param identifier the identifier of the sarcophagus * @param resurrectionTime new resurrection time for the rewrapped * sarcophagus * @param diggingFee new digging fee for the rewrapped sarcophagus * @param bounty new bounty for the rewrapped sarcophagus * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the rewrap was successful */ function rewrapSarcophagus( Datas.Data storage data, bytes32 identifier, uint256 resurrectionTime, uint256 diggingFee, uint256 bounty, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that the embalmer is making this transaction Utils.sarcophagusUpdater(sarc.embalmer); // verify that both the current resurrection time, and the new // resurrection time, are in the future Utils.resurrectionInFuture(sarc.resurrectionTime); Utils.resurrectionInFuture(resurrectionTime); // load the archaeologist Types.Archaeologist storage arch = data.archaeologists[sarc.archaeologist]; // check that the sarcophagus updated parameters fit within the // archaeologist's parameters Utils.withinArchaeologistLimits( resurrectionTime, diggingFee, bounty, arch.maximumResurrectionTime, arch.minimumDiggingFee, arch.minimumBounty ); // transfer the new digging fee from embalmer to this contract sarcoToken.transferFrom(msg.sender, address(this), diggingFee); // transfer the old digging fee to the archaeologist sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee); // calculate the amount of archaeologist's bond to lock up uint256 cursedBondAmount = Archaeologists.getCursedBond(diggingFee, bounty); // if new cursed bond amount is greater than current cursed bond // amount, calculate difference and lock it up. if it's less than, // calculate difference and free it up. if (cursedBondAmount > sarc.currentCursedBond) { uint256 diff = cursedBondAmount - sarc.currentCursedBond; Archaeologists.lockUpBond(data, sarc.archaeologist, diff); } else if (cursedBondAmount < sarc.currentCursedBond) { uint256 diff = sarc.currentCursedBond - cursedBondAmount; Archaeologists.freeUpBond(data, sarc.archaeologist, diff); } // determine the new grace period for the archaeologist's final proof uint256 gracePeriod = Utils.getGracePeriod(resurrectionTime); // set variarbles on the sarcopahgus sarc.resurrectionTime = resurrectionTime; sarc.diggingFee = diggingFee; sarc.bounty = bounty; sarc.currentCursedBond = cursedBondAmount; sarc.resurrectionWindow = gracePeriod; // emit an event emit Events.RewrapSarcophagus( sarc.assetId, identifier, resurrectionTime, gracePeriod, diggingFee, bounty, cursedBondAmount ); // return true return true; } /** * @notice Given a sarcophagus identifier, preimage, and private key, * verify that the data is valid and close out that sarcophagus * @param data the system's data struct instance * @param identifier the identifier of the sarcophagus * @param privateKey the archaeologist's private key which will decrypt the * @param sarcoToken the SARCO token used for payment handling * outer layer of the encrypted payload on Arweave * @return bool indicating that the unwrap was successful */ function unwrapSarcophagus( Datas.Data storage data, bytes32 identifier, bytes32 privateKey, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that we're in the resurrection window Utils.unwrapTime(sarc.resurrectionTime, sarc.resurrectionWindow); // verify that the given private key derives the public key on the // sarcophagus require( PrivateKeys.keyVerification( privateKey, sarc.archaeologistPublicKey ), "!privateKey" ); // save that private key onto the sarcophagus model sarc.privateKey = privateKey; // load up the archaeologist Types.Archaeologist memory arch = data.archaeologists[sarc.archaeologist]; // transfer the Digging fee and bounty over to the archaeologist sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee + sarc.bounty); // free up the archaeologist's cursed bond, because this sarcophagus is // done Archaeologists.freeUpBond( data, sarc.archaeologist, sarc.currentCursedBond ); // set the sarcophagus to Done sarc.state = Types.SarcophagusStates.Done; // save this successful sarcophagus against the archaeologist data.archaeologistSuccesses[sarc.archaeologist].push(identifier); // emit an event emit Events.UnwrapSarcophagus(sarc.assetId, identifier, privateKey); // return true return true; } /** * @notice Given a sarcophagus, accuse the archaeologist for unwrapping the * sarcophagus early * @param data the system's data struct instance * @param identifier the identifier of the sarcophagus * @param singleHash the preimage of the sarcophagus identifier * @param paymentAddress the address to receive payment for accusing the * archaeologist * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the accusal was successful */ function accuseArchaeologist( Datas.Data storage data, bytes32 identifier, bytes memory singleHash, address paymentAddress, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that the resurrection time is in the future Utils.resurrectionInFuture(sarc.resurrectionTime); // verify that the accuser has data which proves that the archaeologist // released the payload too early Utils.hashCheck(identifier, singleHash); // reward this transaction's caller, and the embalmer, with the cursed // bond, and refund the rest of the payment (bounty and digging fees) // back to the embalmer (uint256 halfToSender, uint256 halfToEmbalmer) = splitSend(data, paymentAddress, sarc, sarcoToken); // save the accusal against the archaeologist data.archaeologistAccusals[sarc.archaeologist].push(identifier); // update sarcophagus state to Done sarc.state = Types.SarcophagusStates.Done; // emit an event emit Events.AccuseArchaeologist( identifier, msg.sender, halfToSender, halfToEmbalmer ); // return true return true; } /** * @notice Extends a sarcophagus resurrection time into infinity * effectively signaling that the sarcophagus is over and should never be * resurrected * @param data the system's data struct instance * @param identifier the identifier of the sarcophagus * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the bury was successful */ function burySarcophagus( Datas.Data storage data, bytes32 identifier, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that the embalmer made this transaction Utils.sarcophagusUpdater(sarc.embalmer); // verify that the existing resurrection time is in the future Utils.resurrectionInFuture(sarc.resurrectionTime); // load the archaeologist Types.Archaeologist storage arch = data.archaeologists[sarc.archaeologist]; // free the archaeologist's bond, because this sarcophagus is over Archaeologists.freeUpBond( data, sarc.archaeologist, sarc.currentCursedBond ); // transfer the digging fee to the archae sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee); // set the resurrection time of this sarcopahgus at maxint sarc.resurrectionTime = 2**256 - 1; // update sarcophagus state to Done sarc.state = Types.SarcophagusStates.Done; // emit an event emit Events.BurySarcophagus(identifier); // return true return true; } /** * @notice Clean up a sarcophagus whose resurrection time and window have * passed. Callable by anyone. * @param data the system's data struct instance * @param identifier the identifier of the sarcophagus * @param paymentAddress the address to receive payment for cleaning up the * sarcophagus * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the clean up was successful */ function cleanUpSarcophagus( Datas.Data storage data, bytes32 identifier, address paymentAddress, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that the resurrection window has expired require( sarc.resurrectionTime + sarc.resurrectionWindow < block.timestamp, "sarcophagus resurrection period must be in the past" ); // reward this transaction's caller, and the embalmer, with the cursed // bond, and refund the rest of the payment (bounty and digging fees) // back to the embalmer (uint256 halfToSender, uint256 halfToEmbalmer) = splitSend(data, paymentAddress, sarc, sarcoToken); // save the cleanup against the archaeologist data.archaeologistCleanups[sarc.archaeologist].push(identifier); // update sarcophagus state to Done sarc.state = Types.SarcophagusStates.Done; // emit an event emit Events.CleanUpSarcophagus( identifier, msg.sender, halfToSender, halfToEmbalmer ); // return true return true; } } // File: contracts/Sarcophagus.sol pragma solidity ^0.8.0; /** * @title The main Sarcophagus system contract * @notice This contract implements the entire public interface for the * Sarcophagus system * * Sarcophagus implements a Dead Man's Switch using the Ethereum network as * the official source of truth for the switch (the "sarcophagus"), the Arweave * blockchain as the data storage layer for the encrypted payload, and a * decentralized network of secret-holders (the "archaeologists") who are * responsible for keeping a private key secret until the dead man's switch is * activated (via inaction by the "embalmer", the creator of the sarcophagus). * * @dev All function calls "proxy" down to functions implemented in one of * many libraries */ contract Sarcophagus is Initializable { // keep a reference to the SARCO token, which is used for payments // throughout the system IERC20 public sarcoToken; // all system data is stored within this single instance (_data) of the // Data struct Datas.Data private _data; /** * @notice Contract initializer * @param _sarcoToken The address of the SARCO token */ function initialize(address _sarcoToken) public initializer { sarcoToken = IERC20(_sarcoToken); emit Events.Creation(_sarcoToken); } /** * @notice Return the number of archaeologists that have been registered * @return total registered archaeologist count */ function archaeologistCount() public view virtual returns (uint256) { return _data.archaeologistAddresses.length; } /** * @notice Given an index (of the full archaeologist array), return the * archaeologist address at that index * @param index The index of the registered archaeologist * @return address of the archaeologist */ function archaeologistAddresses(uint256 index) public view virtual returns (address) { return _data.archaeologistAddresses[index]; } /** * @notice Given an archaeologist address, return that archaeologist's * profile * @param account The archaeologist account's address * @return the Archaeologist object */ function archaeologists(address account) public view virtual returns (Types.Archaeologist memory) { return _data.archaeologists[account]; } /** * @notice Return the total number of sarcophagi that have been created * @return the number of sarcophagi that have ever been created */ function sarcophagusCount() public view virtual returns (uint256) { return _data.sarcophagusIdentifiers.length; } /** * @notice Return the unique identifier of a sarcophagus, given it's index * @param index The index of the sarcophagus * @return the unique identifier of the given sarcophagus */ function sarcophagusIdentifier(uint256 index) public view virtual returns (bytes32) { return _data.sarcophagusIdentifiers[index]; } /** * @notice Returns the count of sarcophagi created by a specific embalmer * @param embalmer The address of the given embalmer * @return the number of sarcophagi which have been created by an embalmer */ function embalmerSarcophagusCount(address embalmer) public view virtual returns (uint256) { return _data.embalmerSarcophaguses[embalmer].length; } /** * @notice Returns the sarcophagus unique identifier for a given embalmer * and index * @param embalmer The address of an embalmer * @param index The index of the embalmer's list of sarcophagi * @return the double hash associated with the index of the embalmer's * sarcophagi */ function embalmerSarcophagusIdentifier(address embalmer, uint256 index) public view virtual returns (bytes32) { return _data.embalmerSarcophaguses[embalmer][index]; } /** * @notice Returns the count of sarcophagi created for a specific * archaeologist * @param archaeologist The address of the given archaeologist * @return the number of sarcophagi which have been created for an * archaeologist */ function archaeologistSarcophagusCount(address archaeologist) public view virtual returns (uint256) { return _data.archaeologistSarcophaguses[archaeologist].length; } /** * @notice Returns the sarcophagus unique identifier for a given * archaeologist and index * @param archaeologist The address of an archaeologist * @param index The index of the archaeologist's list of sarcophagi * @return the identifier associated with the index of the archaeologist's * sarcophagi */ function archaeologistSarcophagusIdentifier( address archaeologist, uint256 index ) public view virtual returns (bytes32) { return _data.archaeologistSarcophaguses[archaeologist][index]; } /** * @notice Returns the count of sarcophagi created for a specific recipient * @param recipient The address of the given recipient * @return the number of sarcophagi which have been created for a recipient */ function recipientSarcophagusCount(address recipient) public view virtual returns (uint256) { return _data.recipientSarcophaguses[recipient].length; } /** * @notice Returns the sarcophagus unique identifier for a given recipient * and index * @param recipient The address of a recipient * @param index The index of the recipient's list of sarcophagi * @return the identifier associated with the index of the recipient's * sarcophagi */ function recipientSarcophagusIdentifier(address recipient, uint256 index) public view virtual returns (bytes32) { return _data.recipientSarcophaguses[recipient][index]; } /** * @notice Returns the count of successful sarcophagi completed by the * archaeologist * @param archaeologist The address of the given archaeologist * @return the number of sarcophagi which have been successfully completed * by the archaeologist */ function archaeologistSuccessesCount(address archaeologist) public view virtual returns (uint256) { return _data.archaeologistSuccesses[archaeologist].length; } /** * @notice Returns the sarcophagus unique identifier for a given archaeologist * and index of successful sarcophagi * @param archaeologist The address of an archaeologist * @param index The index of the archaeologist's list of successfully * completed sarcophagi * @return the identifier associated with the index of the archaeologist's * successfully completed sarcophagi */ function archaeologistSuccessesIdentifier( address archaeologist, uint256 index ) public view returns (bytes32) { return _data.archaeologistSuccesses[archaeologist][index]; } /** * @notice Returns the count of cancelled sarcophagi from the archaeologist * @param archaeologist The address of the given archaeologist * @return the number of cancelled sarcophagi from the archaeologist */ function archaeologistCancelsCount(address archaeologist) public view virtual returns (uint256) { return _data.archaeologistCancels[archaeologist].length; } /** * @notice Returns the sarcophagus unique identifier for a given archaeologist * and index of the cancelled sarcophagi * @param archaeologist The address of an archaeologist * @param index The index of the archaeologist's cancelled sarcophagi * @return the identifier associated with the index of the archaeologist's * cancelled sarcophagi */ function archaeologistCancelsIdentifier( address archaeologist, uint256 index ) public view virtual returns (bytes32) { return _data.archaeologistCancels[archaeologist][index]; } /** * @notice Returns the count of accused sarcophagi from the archaeologist * @param archaeologist The address of the given archaeologist * @return the number of accused sarcophagi from the archaeologist */ function archaeologistAccusalsCount(address archaeologist) public view virtual returns (uint256) { return _data.archaeologistAccusals[archaeologist].length; } /** * @notice Returns the sarcophagus unique identifier for a given * archaeologist and index of the accused sarcophagi * @param archaeologist The address of an archaeologist * @param index The index of the archaeologist's accused sarcophagi * @return the identifier associated with the index of the archaeologist's * accused sarcophagi */ function archaeologistAccusalsIdentifier( address archaeologist, uint256 index ) public view virtual returns (bytes32) { return _data.archaeologistAccusals[archaeologist][index]; } /** * @notice Returns the count of cleaned-up sarcophagi from the * archaeologist * @param archaeologist The address of the given archaeologist * @return the number of cleaned-up sarcophagi from the archaeologist */ function archaeologistCleanupsCount(address archaeologist) public view virtual returns (uint256) { return _data.archaeologistCleanups[archaeologist].length; } /** * @notice Returns the sarcophagus unique identifier for a given * archaeologist and index of the cleaned-up sarcophagi * @param archaeologist The address of an archaeologist * @param index The index of the archaeologist's accused sarcophagi * @return the identifier associated with the index of the archaeologist's * leaned-up sarcophagi */ function archaeologistCleanupsIdentifier( address archaeologist, uint256 index ) public view virtual returns (bytes32) { return _data.archaeologistCleanups[archaeologist][index]; } /** * @notice Returns sarcophagus data given an indentifier * @param identifier the unique identifier a sarcophagus * @return sarc the Sarcophagus object */ function sarcophagus(bytes32 identifier) public view virtual returns (Types.Sarcophagus memory) { return _data.sarcophaguses[identifier]; } /** * @notice Registers a new archaeologist in the system * @param currentPublicKey the public key to be used in the first * sarcophagus * @param endpoint where to contact this archaeologist on the internet * @param paymentAddress all collected payments for the archaeologist will * be sent here * @param feePerByte amount of SARCO tokens charged per byte of storage * being sent to Arweave * @param minimumBounty the minimum bounty for a sarcophagus that the * archaeologist will accept * @param minimumDiggingFee the minimum digging fee for a sarcophagus that * the archaeologist will accept * @param maximumResurrectionTime the maximum resurrection time for a * sarcophagus that the archaeologist will accept, in relative terms (i.e. * "1 year" is 31536000 (seconds)) * @param freeBond the amount of SARCO bond that the archaeologist wants * to start with * @return index of the new archaeologist */ function registerArchaeologist( bytes memory currentPublicKey, string memory endpoint, address paymentAddress, uint256 feePerByte, uint256 minimumBounty, uint256 minimumDiggingFee, uint256 maximumResurrectionTime, uint256 freeBond ) public virtual returns (uint256) { return Archaeologists.registerArchaeologist( _data, currentPublicKey, endpoint, paymentAddress, feePerByte, minimumBounty, minimumDiggingFee, maximumResurrectionTime, freeBond, sarcoToken ); } /** * @notice An archaeologist may update their profile * @param endpoint where to contact this archaeologist on the internet * @param newPublicKey the public key to be used in the next * sarcophagus * @param paymentAddress all collected payments for the archaeologist will * be sent here * @param feePerByte amount of SARCO tokens charged per byte of storage * being sent to Arweave * @param minimumBounty the minimum bounty for a sarcophagus that the * archaeologist will accept * @param minimumDiggingFee the minimum digging fee for a sarcophagus that * the archaeologist will accept * @param maximumResurrectionTime the maximum resurrection time for a * sarcophagus that the archaeologist will accept, in relative terms (i.e. * "1 year" is 31536000 (seconds)) * @param freeBond the amount of SARCO bond that the archaeologist wants * to add to their profile * @return bool indicating that the update was successful */ function updateArchaeologist( string memory endpoint, bytes memory newPublicKey, address paymentAddress, uint256 feePerByte, uint256 minimumBounty, uint256 minimumDiggingFee, uint256 maximumResurrectionTime, uint256 freeBond ) public virtual returns (bool) { return Archaeologists.updateArchaeologist( _data, newPublicKey, endpoint, paymentAddress, feePerByte, minimumBounty, minimumDiggingFee, maximumResurrectionTime, freeBond, sarcoToken ); } /** * @notice Archaeologist can withdraw any of their free bond * @param amount the amount of the archaeologist's free bond that they're * withdrawing * @return bool indicating that the withdrawal was successful */ function withdrawBond(uint256 amount) public virtual returns (bool) { return Archaeologists.withdrawBond(_data, amount, sarcoToken); } /** * @notice Embalmer creates the skeleton for a new sarcopahgus * @param name the name of the sarcophagus * @param archaeologist the address of a registered archaeologist to * assign this sarcophagus to * @param resurrectionTime the resurrection time of the sarcophagus * @param storageFee the storage fee that the archaeologist will receive, * for saving this sarcophagus on Arweave * @param diggingFee the digging fee that the archaeologist will receive at * the first rewrap * @param bounty the bounty that the archaeologist will receive when the * sarcophagus is unwrapped * @param identifier the identifier of the sarcophagus, which is the hash * of the hash of the inner encrypted layer of the sarcophagus * @param recipientPublicKey the public key of the recipient * @return index of the new sarcophagus */ function createSarcophagus( string memory name, address archaeologist, uint256 resurrectionTime, uint256 storageFee, uint256 diggingFee, uint256 bounty, bytes32 identifier, bytes memory recipientPublicKey ) public virtual returns (uint256) { return Sarcophaguses.createSarcophagus( _data, name, archaeologist, resurrectionTime, storageFee, diggingFee, bounty, identifier, recipientPublicKey, sarcoToken ); } /** * @notice Embalmer updates a sarcophagus given it's identifier, after * the archaeologist has uploaded the encrypted payload onto Arweave * @param newPublicKey the archaeologist's new public key, to use for * encrypting the next sarcophagus that they're assigned to * @param identifier the identifier of the sarcophagus * @param assetId the identifier of the encrypted asset on Arweave * @param v signature element * @param r signature element * @param s signature element * @return bool indicating that the update was successful */ function updateSarcophagus( bytes memory newPublicKey, bytes32 identifier, string memory assetId, uint8 v, bytes32 r, bytes32 s ) public virtual returns (bool) { return Sarcophaguses.updateSarcophagus( _data, newPublicKey, identifier, assetId, v, r, s, sarcoToken ); } /** * @notice An embalmer may cancel a sarcophagus if it hasn't been * completely created * @param identifier the identifier of the sarcophagus * @return bool indicating that the cancel was successful */ function cancelSarcophagus(bytes32 identifier) public virtual returns (bool) { return Sarcophaguses.cancelSarcophagus(_data, identifier, sarcoToken); } /** * @notice Embalmer can extend the resurrection time of the sarcophagus, * as long as the previous resurrection time is in the future * @param identifier the identifier of the sarcophagus * @param resurrectionTime new resurrection time for the rewrapped * sarcophagus * @param diggingFee new digging fee for the rewrapped sarcophagus * @param bounty new bounty for the rewrapped sarcophagus * @return bool indicating that the rewrap was successful */ function rewrapSarcophagus( bytes32 identifier, uint256 resurrectionTime, uint256 diggingFee, uint256 bounty ) public virtual returns (bool) { return Sarcophaguses.rewrapSarcophagus( _data, identifier, resurrectionTime, diggingFee, bounty, sarcoToken ); } /** * @notice Given a sarcophagus identifier, preimage, and private key, * verify that the data is valid and close out that sarcophagus * @param identifier the identifier of the sarcophagus * @param privateKey the archaeologist's private key which will decrypt the * outer layer of the encrypted payload on Arweave * @return bool indicating that the unwrap was successful */ function unwrapSarcophagus(bytes32 identifier, bytes32 privateKey) public virtual returns (bool) { return Sarcophaguses.unwrapSarcophagus( _data, identifier, privateKey, sarcoToken ); } /** * @notice Given a sarcophagus, accuse the archaeologist for unwrapping the * sarcophagus early * @param identifier the identifier of the sarcophagus * @param singleHash the preimage of the sarcophagus identifier * @param paymentAddress the address to receive payment for accusing the * archaeologist * @return bool indicating that the accusal was successful */ function accuseArchaeologist( bytes32 identifier, bytes memory singleHash, address paymentAddress ) public virtual returns (bool) { return Sarcophaguses.accuseArchaeologist( _data, identifier, singleHash, paymentAddress, sarcoToken ); } /** * @notice Extends a sarcophagus resurrection time into infinity * effectively signaling that the sarcophagus is over and should never be * resurrected * @param identifier the identifier of the sarcophagus * @return bool indicating that the bury was successful */ function burySarcophagus(bytes32 identifier) public virtual returns (bool) { return Sarcophaguses.burySarcophagus(_data, identifier, sarcoToken); } /** * @notice Clean up a sarcophagus whose resurrection time and window have * passed. Callable by anyone. * @param identifier the identifier of the sarcophagus * @param paymentAddress the address to receive payment for cleaning up the * sarcophagus * @return bool indicating that the clean up was successful */ function cleanUpSarcophagus(bytes32 identifier, address paymentAddress) public virtual returns (bool) { return Sarcophaguses.cleanUpSarcophagus( _data, identifier, paymentAddress, sarcoToken ); } }
* @notice Embalmer can extend the resurrection time of the sarcophagus, as long as the previous resurrection time is in the future @param data the system's data struct instance @param identifier the identifier of the sarcophagus @param resurrectionTime new resurrection time for the rewrapped sarcophagus @param diggingFee new digging fee for the rewrapped sarcophagus @param bounty new bounty for the rewrapped sarcophagus @param sarcoToken the SARCO token used for payment handling @return bool indicating that the rewrap was successful/ load the sarcophagus, and make sure it exists verify that the embalmer is making this transaction verify that both the current resurrection time, and the new resurrection time, are in the future load the archaeologist check that the sarcophagus updated parameters fit within the archaeologist's parameters transfer the new digging fee from embalmer to this contract transfer the old digging fee to the archaeologist calculate the amount of archaeologist's bond to lock up if new cursed bond amount is greater than current cursed bond amount, calculate difference and lock it up. if it's less than, calculate difference and free it up.
function rewrapSarcophagus( Datas.Data storage data, bytes32 identifier, uint256 resurrectionTime, uint256 diggingFee, uint256 bounty, IERC20 sarcoToken ) public returns (bool) { Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); Utils.sarcophagusUpdater(sarc.embalmer); Utils.resurrectionInFuture(sarc.resurrectionTime); Utils.resurrectionInFuture(resurrectionTime); Types.Archaeologist storage arch = data.archaeologists[sarc.archaeologist]; Utils.withinArchaeologistLimits( resurrectionTime, diggingFee, bounty, arch.maximumResurrectionTime, arch.minimumDiggingFee, arch.minimumBounty ); sarcoToken.transferFrom(msg.sender, address(this), diggingFee); sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee); uint256 cursedBondAmount = Archaeologists.getCursedBond(diggingFee, bounty); if (cursedBondAmount > sarc.currentCursedBond) { uint256 diff = cursedBondAmount - sarc.currentCursedBond; Archaeologists.lockUpBond(data, sarc.archaeologist, diff); uint256 diff = sarc.currentCursedBond - cursedBondAmount; Archaeologists.freeUpBond(data, sarc.archaeologist, diff); } sarc.diggingFee = diggingFee; sarc.bounty = bounty; sarc.currentCursedBond = cursedBondAmount; sarc.resurrectionWindow = gracePeriod; sarc.assetId, identifier, resurrectionTime, gracePeriod, diggingFee, bounty, cursedBondAmount ); }
2,451,190
[ 1, 1514, 70, 287, 6592, 848, 2133, 326, 400, 295, 9329, 813, 434, 326, 272, 11828, 23169, 346, 407, 16, 487, 1525, 487, 326, 2416, 400, 295, 9329, 813, 353, 316, 326, 3563, 225, 501, 326, 2619, 1807, 501, 1958, 791, 225, 2756, 326, 2756, 434, 326, 272, 11828, 23169, 346, 407, 225, 400, 295, 9329, 950, 394, 400, 295, 9329, 813, 364, 326, 283, 18704, 272, 11828, 23169, 346, 407, 225, 3097, 1998, 14667, 394, 3097, 1998, 14036, 364, 326, 283, 18704, 272, 11828, 23169, 346, 407, 225, 324, 592, 93, 394, 324, 592, 93, 364, 326, 283, 18704, 272, 11828, 23169, 346, 407, 225, 272, 297, 2894, 1345, 326, 348, 985, 3865, 1147, 1399, 364, 5184, 5057, 327, 1426, 11193, 716, 326, 283, 4113, 1703, 6873, 19, 1262, 326, 272, 11828, 23169, 346, 407, 16, 471, 1221, 3071, 518, 1704, 3929, 716, 326, 31265, 287, 6592, 353, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 283, 4113, 55, 11828, 23169, 346, 407, 12, 203, 3639, 6168, 345, 18, 751, 2502, 501, 16, 203, 3639, 1731, 1578, 2756, 16, 203, 3639, 2254, 5034, 400, 295, 9329, 950, 16, 203, 3639, 2254, 5034, 3097, 1998, 14667, 16, 203, 3639, 2254, 5034, 324, 592, 93, 16, 203, 3639, 467, 654, 39, 3462, 272, 297, 2894, 1345, 203, 565, 262, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 7658, 18, 55, 11828, 23169, 346, 407, 2502, 272, 11828, 273, 501, 18, 87, 11828, 23169, 346, 6117, 63, 5644, 15533, 203, 3639, 272, 11828, 23169, 346, 407, 1119, 12, 87, 11828, 18, 2019, 16, 7658, 18, 55, 11828, 23169, 346, 407, 7629, 18, 4002, 1769, 203, 203, 3639, 6091, 18, 87, 11828, 23169, 346, 407, 15305, 12, 87, 11828, 18, 351, 70, 287, 6592, 1769, 203, 203, 3639, 6091, 18, 455, 295, 9329, 382, 4118, 12, 87, 11828, 18, 455, 295, 9329, 950, 1769, 203, 3639, 6091, 18, 455, 295, 9329, 382, 4118, 12, 455, 295, 9329, 950, 1769, 203, 203, 3639, 7658, 18, 686, 8838, 73, 3966, 376, 2502, 6637, 273, 203, 5411, 501, 18, 991, 8906, 3966, 1486, 63, 87, 11828, 18, 991, 8906, 3966, 376, 15533, 203, 203, 3639, 6091, 18, 25850, 686, 8838, 73, 3966, 376, 12768, 12, 203, 5411, 400, 295, 9329, 950, 16, 203, 5411, 3097, 1998, 14667, 16, 203, 5411, 324, 592, 93, 16, 203, 5411, 6637, 18, 15724, 607, 295, 9329, 950, 16, 203, 5411, 6637, 18, 15903, 4907, 1998, 14667, 16, 203, 5411, 2 ]
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 private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title DealsRootStorage * @dev Storage for precalculated merkle roots. */ contract DealsRootStorage is Ownable { mapping(uint256 => bytes32) roots; uint256 public lastTimestamp = 0; /** * @dev Sets merkle root at the specified timestamp. */ function setRoot(uint256 _timestamp, bytes32 _root) onlyOwner public returns (bool) { require(_timestamp > 0); require(roots[_timestamp] == 0); roots[_timestamp] = _root; lastTimestamp = _timestamp; return true; } /** * @dev Gets last available merkle root. */ function lastRoot() public view returns (bytes32) { return roots[lastTimestamp]; } /** * @dev Gets merkle root by the specified timestamp. */ function getRoot(uint256 _timestamp) public view returns (bytes32) { return roots[_timestamp]; } }
* @title DealsRootStorage @dev Storage for precalculated merkle roots./
contract DealsRootStorage is Ownable { mapping(uint256 => bytes32) roots; uint256 public lastTimestamp = 0; function setRoot(uint256 _timestamp, bytes32 _root) onlyOwner public returns (bool) { require(_timestamp > 0); require(roots[_timestamp] == 0); roots[_timestamp] = _root; lastTimestamp = _timestamp; return true; } function lastRoot() public view returns (bytes32) { return roots[lastTimestamp]; } function getRoot(uint256 _timestamp) public view returns (bytes32) { return roots[_timestamp]; } }
1,037,273
[ 1, 758, 1031, 2375, 3245, 225, 5235, 364, 675, 22113, 30235, 12876, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1505, 1031, 2375, 3245, 353, 14223, 6914, 288, 203, 225, 2874, 12, 11890, 5034, 516, 1731, 1578, 13, 12876, 31, 203, 225, 2254, 5034, 1071, 1142, 4921, 273, 374, 31, 203, 203, 225, 445, 31706, 12, 11890, 5034, 389, 5508, 16, 1731, 1578, 389, 3085, 13, 1338, 5541, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2583, 24899, 5508, 405, 374, 1769, 203, 565, 2583, 12, 22078, 63, 67, 5508, 65, 422, 374, 1769, 203, 203, 565, 12876, 63, 67, 5508, 65, 273, 389, 3085, 31, 203, 565, 1142, 4921, 273, 389, 5508, 31, 203, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 225, 445, 1142, 2375, 1435, 1071, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 565, 327, 12876, 63, 2722, 4921, 15533, 203, 225, 289, 203, 203, 225, 445, 7656, 12, 11890, 5034, 389, 5508, 13, 1071, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 565, 327, 12876, 63, 67, 5508, 15533, 203, 225, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/5/0xdE4c870F36a614E44bd00f987B22F4c4D48718F3/sources/contracts/base/MetawinERC721Extensions/MetawinERC721Vault.sol
add its staking time to the cumulative count
currentCumulative+=current;
16,866,984
[ 1, 1289, 2097, 384, 6159, 813, 358, 326, 15582, 1056, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 7734, 783, 39, 11276, 15, 33, 2972, 31, 5397, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0x7511871bc4037ACfAE72c14cF736B2effe982E6c/sources/CNES/CarbonCoin/ETH_Official/base.sol
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.
abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () public { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } modifier isHuman() { require(tx.origin == msg.sender, "Humans only"); _; } }
11,530,237
[ 1, 38, 11887, 634, 854, 1898, 19326, 2353, 2254, 5034, 578, 1281, 618, 716, 5530, 731, 279, 1983, 2076, 2724, 1517, 1045, 1674, 24169, 392, 2870, 348, 7783, 358, 1122, 855, 326, 4694, 1807, 2939, 16, 1453, 326, 4125, 9830, 731, 635, 326, 1250, 16, 471, 1508, 1045, 1473, 18, 1220, 353, 326, 5274, 1807, 1652, 3558, 5314, 6835, 28844, 471, 4407, 2308, 310, 16, 471, 518, 2780, 506, 5673, 18, 1021, 924, 3832, 1661, 17, 7124, 460, 7297, 6314, 279, 2831, 1898, 19326, 16, 1496, 316, 7829, 326, 16255, 603, 3614, 745, 358, 1661, 426, 8230, 970, 903, 506, 2612, 316, 3844, 18, 7897, 16255, 87, 854, 3523, 1845, 358, 279, 11622, 434, 326, 2078, 2492, 1807, 16189, 16, 518, 353, 3796, 358, 3455, 2182, 4587, 316, 6088, 3007, 333, 1245, 16, 358, 10929, 326, 18067, 434, 326, 1983, 16255, 19283, 1368, 5426, 18, 2, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 868, 8230, 12514, 16709, 288, 203, 203, 565, 2254, 5034, 3238, 5381, 389, 4400, 67, 12278, 2056, 273, 404, 31, 203, 565, 2254, 5034, 3238, 5381, 389, 12278, 2056, 273, 576, 31, 203, 203, 565, 2254, 5034, 3238, 389, 2327, 31, 203, 203, 565, 3885, 1832, 1071, 288, 203, 3639, 389, 2327, 273, 389, 4400, 67, 12278, 2056, 31, 203, 565, 289, 203, 203, 565, 9606, 1661, 426, 8230, 970, 1435, 288, 203, 3639, 2583, 24899, 2327, 480, 389, 12278, 2056, 16, 315, 426, 8230, 12514, 16709, 30, 283, 8230, 970, 745, 8863, 203, 203, 3639, 389, 2327, 273, 389, 12278, 2056, 31, 203, 203, 3639, 389, 31, 203, 203, 3639, 389, 2327, 273, 389, 4400, 67, 12278, 2056, 31, 203, 565, 289, 203, 203, 565, 9606, 27803, 6925, 1435, 288, 203, 3639, 2583, 12, 978, 18, 10012, 422, 1234, 18, 15330, 16, 315, 44, 379, 634, 1338, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at polygonscan.com on 2021-11-04 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; // import "hardhat/console.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { 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; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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, 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 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); 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); } /** @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); } /** * @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); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @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); } } } } interface IGrowthVault { function strategy() external view returns (address); function deposit(uint256 _amount) external; function earn() external; function getCurrentStrategy() external view returns ( address _liquidityRouter, address _lpToken, address _token1, address _token0, address _farm, uint256 _pid ); } interface Ifarm { function DINO() external view returns (address); function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function leaveStaking(uint256 _amount) external; function emergencyWithdraw(uint256 _pid) external; function poolInfo(uint256) external view returns(address lpToken, uint allocPoint, uint lastRewardBlock, uint accSpiritPerShare, uint16 depositFeeBP); } interface IfarmWOpid { struct Profit { uint usd; uint hunny; uint bnb; } struct APY { uint usd; uint hunny; uint bnb; } struct UserInfo { uint balance; uint principal; uint available; Profit profit; uint poolTVL; APY poolAPY; } function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256); function pendingSushi(address _user) external view returns (uint256); function emergencyWithdraw(uint256 _pid) external; function info(address account) external view returns (UserInfo memory); } interface IRouter { function factory() external view returns (address); function WETH() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IPair { function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112, uint112, uint32); function totalSupply() external view returns (uint256); function mint(address to) external returns (uint256); } /** * @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; } } /** * @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"); } } } library TransferHelper { function safeTransferBNB(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferBNB: BNB transfer failed'); } } interface IWBNB { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function withdraw(uint) external; } /** * @dev Implementation of a vault to deposit funds for yield optimizing. * This is the contract that receives funds and that users interface with. * The yield optimizing strategy itself is implemented in a separate 'Strategy.sol' contract. */ contract GrowthVault is ERC20, Ownable { using SafeERC20 for IERC20; using Address for address; struct StrategyInfo { address liquidityRouter; address lpToken; uint256 pid; uint256 totalLP; uint256 totalCapital; address farm; address token0; address token1; } // Info of each strategy for LP tokens. // nameID, strategy obj mapping(uint256 => StrategyInfo) private strategyInfo; mapping(address => uint256) private requestBlock; mapping(uint256 => bool) private nameExist; uint256[] private names; uint256 public constant withdrawFee = 15; // 15% uint256 public constant toleranceLevelPercent = 1; // 1% uint256 public totalFeeUSDT; uint256 public REQUIRED_NUMBER_OF_BLOCKS = 4; address public government; address public YELtoken; address public yelLiquidityRouter; address public USDT; uint256 private pid; uint256 private nameID; uint256 private constant NONE_PID_VALUE = 999999; uint256 private constant differencePercent = 1; // 1% address private farm; address private token0; address private token1; address private WETH; address private liquidityRouter; uint256 public pendingFee; // in native tokens uint256 public pendingFeeInCakes; address private lpToken; // TODO: remove strategy // TODO: userСapital добавить при каждом вводе кошелька пользователя и вывести в WBNB event YELswapped(uint256 percent); event DepositToVault(uint256 amount); event WithdrawFromVault(uint256 amount); event Earn(uint256 amount); event PartialMigrate(uint256 amount); event Migrate(uint256 amount); event AutoCompound(); modifier onlyOwnerOrGovernment() { require( owner() == _msgSender() || government == _msgSender(), "Ownable: caller is not the owner or government" ); _; } modifier canWithdraw() { uint256 currentBlock = block.number; if(requestBlock[msg.sender] == 0) { requestBlock[msg.sender] = currentBlock; } else if(currentBlock - requestBlock[msg.sender] >= REQUIRED_NUMBER_OF_BLOCKS) { _; } else { revert("Difference of blocks is less then REQUIRED_NUMBER_OF_BLOCKS"); } } /** * @dev Sets the value of {token} to the token that the vault will * hold as underlying value. It initializes the vault's own token. * This token is minted when someone does a deposit. It is burned in order * to withdraw the corresponding portion of the underlying assets. */ constructor( string memory name__, string memory symbol__, address _lpToken, uint256 _pid, uint256 _nameID, address _farm, address _liquidityRouter, address _USDT, address _YELtoken, address _yelLiquidityRouter) ERC20(name__, symbol__) { require(_lpToken != address(0), "The address of lp token can not be a zero address"); require(_farm != address(0), "The address of farm can not be a zero address"); require(_liquidityRouter != address(0), "The address of liquidityRouter can not be a zero address"); require(_YELtoken != address(0), "The address of YELtoken can not be a zero address"); _setBaseAddresses(_farm, _liquidityRouter, _lpToken, _pid, _nameID); yelLiquidityRouter = _yelLiquidityRouter; YELtoken = _YELtoken; WETH = IRouter(_liquidityRouter).WETH(); USDT = _USDT; } function getCurrentStrategy() public view returns ( address _liquidityRouter, address _lpToken, address _token1, address _token0, address _farm, uint256 _pid) { _liquidityRouter = liquidityRouter; _lpToken = lpToken; _token1 = token1; _token0 = token0; _farm = farm; _pid = pid; } function getNamesOfStrategies() public view returns (uint256[] memory) { return names; } function getStrategyInfo(uint256 _nameID) public view returns ( address _liquidityRouter, address _lpToken, address _token1, address _token0, address _farm, uint256 _pid) { StrategyInfo memory strategyObj = strategyInfo[_nameID]; _liquidityRouter = strategyObj.liquidityRouter; _lpToken = strategyObj.lpToken; _token1 = strategyObj.token1; _token0 = strategyObj.token0; _farm = strategyObj.farm; _pid = strategyObj.pid; } function updateTotalCapital() public returns (uint256) { uint256 totalCapital = 0; uint256 _nameID; StrategyInfo storage strategyObj; uint256 totalLP; uint256 _token0Value; uint256 _token1Value; uint256[] memory amounts; address[] memory path = new address[](2); for (uint256 i; i < names.length; i++) { _nameID = names[i]; strategyObj = strategyInfo[_nameID]; if(strategyObj.pid < NONE_PID_VALUE) { totalLP = _getAmountLPFromStrategy(strategyObj.farm, strategyObj.pid); } else { totalLP = _getAmountLPFromStrategyWOpid(strategyObj.farm); } if(totalLP > 0) { (_token0Value, _token1Value) = _getTokenValues(strategyObj.lpToken, totalLP); // calculates how many nativeToken for tokens path[1] = WETH; if(strategyObj.token0 == WETH) { path[0] = strategyObj.token1; amounts = IRouter(strategyObj.liquidityRouter).getAmountsOut(_token1Value, path); strategyObj.totalCapital = amounts[1]; totalCapital += strategyObj.totalCapital; } else if (strategyObj.token1 == WETH) { path[0] = strategyObj.token0; amounts = IRouter(strategyObj.liquidityRouter).getAmountsOut(_token0Value, path); strategyObj.totalCapital = amounts[1]; totalCapital += strategyObj.totalCapital; } else { path[0] = strategyObj.token0; amounts = IRouter(strategyObj.liquidityRouter).getAmountsOut(_token0Value, path); strategyObj.totalCapital = amounts[1]; totalCapital += strategyObj.totalCapital; path[0] = strategyObj.token1; amounts = IRouter(strategyObj.liquidityRouter).getAmountsOut(_token1Value, path); strategyObj.totalCapital = amounts[1]; totalCapital += strategyObj.totalCapital; } } } return totalCapital; } function addStrategy( address _newStrategy, uint256 _pid, address _lpToken, address _liquidityRouter, uint256 _nameID) onlyOwner external { require(_newStrategy != address(0), "newStrategy can not be a zero address"); require(_lpToken != address(0), "lpToken can not be a zero address"); require(_liquidityRouter != address(0), "liquidityRouter can not be a zero address"); _addStrategy(_newStrategy, _pid, _lpToken, _liquidityRouter, _nameID); } function addStrategyWOpid( address _newStrategy, address _lpToken, address _liquidityRouter, uint256 _nameID) onlyOwner external { require(_newStrategy != address(0), "newStrategy can not be a zero address"); require(_lpToken != address(0), "lpToken can not be a zero address"); require(_liquidityRouter != address(0), "liquidityRouter can not be a zero address"); _addStrategy(_newStrategy, NONE_PID_VALUE, _lpToken, _liquidityRouter, _nameID); } function setGovernment(address _government) external onlyOwner { require(_government != address(0), "The address of government can not be a zero address"); government = _government; } function withdrawTokensFee() onlyOwner public { require( _getBalanceOfToken(USDT) > 0, "GrowthVault: USDT balance should be more then 0" ); IERC20(USDT).transfer(msg.sender, totalFeeUSDT); totalFeeUSDT = 0; } function earn() public { _earn(farm, pid, _getBalanceOfToken(lpToken)); } function autoCompound() public { uint256 _nameID; uint256 _amount; address _cakeToken; address[] memory path = new address[](2); address[] memory path1 = new address[](3); StrategyInfo memory strategyObj; uint256[] memory amounts; uint256 rewardsFeeInWETH; uint256 rewardsFeeInCakes; uint256 rewardBalance; uint256 desired; for (uint256 i; i < names.length; i++) { _nameID = names[i]; strategyObj = strategyInfo[_nameID]; if(strategyObj.pid < NONE_PID_VALUE) { _amount = _getAmountLPFromStrategy(strategyObj.farm, strategyObj.pid); } else { _amount = _getAmountLPFromStrategyWOpid(strategyObj.farm); } if (_amount > 0) { _withdrawFromStrategy(_nameID, _amount); _cakeToken = _getCakeToken(strategyObj.farm); path[0] = _cakeToken; path[1] = WETH; rewardBalance = getAvalaibleCakes(_cakeToken); IERC20(_cakeToken).safeApprove(strategyObj.liquidityRouter, 0); IERC20(_cakeToken).safeApprove(strategyObj.liquidityRouter, type(uint256).max); rewardsFeeInCakes = _calculateAmountFee(rewardBalance) + pendingFeeInCakes; amounts = IRouter(strategyObj.liquidityRouter).getAmountsOut(rewardsFeeInCakes, path); if(amounts[1] > 100) { IRouter(strategyObj.liquidityRouter).swapExactTokensForTokens( rewardsFeeInCakes, amounts[1] - (amounts[1]*toleranceLevelPercent)/100, path, address(this), block.timestamp+1 minutes ); pendingFeeInCakes = 0; } else { pendingFeeInCakes += rewardsFeeInCakes; } path[0] = WETH; path[1] = USDT; rewardsFeeInWETH = _getBalanceOfToken(WETH); amounts = IRouter(strategyObj.liquidityRouter).getAmountsOut(rewardsFeeInWETH, path); if(amounts[1] > 100) { IRouter(strategyObj.liquidityRouter).swapExactTokensForTokens( rewardsFeeInWETH, amounts[1] - (amounts[1]*toleranceLevelPercent)/100, path, address(this), block.timestamp+1 minutes ); pendingFee = 0; totalFeeUSDT = _getBalanceOfToken(USDT); } else { pendingFee += rewardsFeeInWETH; } rewardBalance = getAvalaibleCakes(_cakeToken); path1[0] = _cakeToken; path1[1] = WETH; path1[2] = _cakeToken; amounts = IRouter(strategyObj.liquidityRouter).getAmountsOut(rewardBalance, path1); if(amounts[1] > 100) { IRouter(strategyObj.liquidityRouter).swapExactTokensForTokens( rewardBalance, amounts[1] - (amounts[1]*toleranceLevelPercent)/100, path1, address(this), block.timestamp+1 minutes ); amounts = IRouter(strategyObj.liquidityRouter).getAmountsOut( _getBalanceOfToken(strategyObj.token0), path); if(amounts[1] <= _getBalanceOfToken(strategyObj.token1)) { desired = amounts[1]; } else { desired = _getBalanceOfToken(strategyObj.token1); } IERC20(strategyObj.token0).transfer(lpToken, _getBalanceOfToken(strategyObj.token0)); IERC20(strategyObj.token1).transfer(lpToken, desired); IPair(lpToken).mint(address(this)); } _earn(strategyObj.farm, strategyObj.pid, _getBalanceOfToken(strategyObj.lpToken)); strategyObj.totalLP = _getAmountLPFromStrategy(strategyObj.farm, strategyObj.pid); // TODO: all other tokens to USDT ? } } updateTotalCapital(); emit AutoCompound(); } receive() external payable { deposit(); } function deposit() public payable { autoCompound(); _approveTokens(token0, token1, liquidityRouter); _addLiquidity(liquidityRouter, token0, token1); earn(); // uint256 totalCapital = updateTotalCapital(); // uint256 percent = (msg.value * 100 * 1000) / (totalCapital); // uint256 shares = percent * totalCapital / 1000; // _mint(msg.sender, shares); // // TODO: excessToUSDT(); ? // emit DepositToVault(msg.value); } function withdraw(uint256 _shares) canWithdraw public { uint256 totalCapital = updateTotalCapital(); // TODO: percent = (_shares/totalShares)*100 autoCompound(); uint256 percent = (_shares * 100 * 100)/(totalCapital * 100); _burn(msg.sender, _shares); _getYELs(percent); uint256 _balance = _getBalanceOfToken(YELtoken); IERC20(YELtoken).transfer(msg.sender, _balance); emit WithdrawFromVault(_balance); } function migrate(address _contract) onlyOwnerOrGovernment public { require(_contract != address(0), "The _contract can not be a zero address"); autoCompound(); (address _newLpToken, address _newliquidityRouter,,,,) = IGrowthVault(_contract).getCurrentStrategy(); _withdrawFromStrategies(); for (uint256 i; i < names.length; i++) { _removeLiquidityAfterWithdraw(names[i]); } (address _token0, address _token1) = _getTokensFromLP(_newLpToken); _addLiquidity(_token0, _token1, _newliquidityRouter); IERC20(_newLpToken).transfer(_contract, _getBalanceOfToken(_newLpToken)); IGrowthVault(_contract).earn(); } function partialMigrate( uint256 _oldNameId, uint256 _amount, uint256 _newNameId) onlyOwnerOrGovernment public { autoCompound(); require(nameExist[_oldNameId], "The _oldNameId value does not exist"); require(nameExist[_newNameId], "The _newNameId value does not exist"); require(_amount > 0, "The _amount value sould be more then ZERO"); // take LP from old strategy _withdrawFromStrategy(_oldNameId, _amount); // swap LP and Cakes to native Token _removeLiquidityAfterWithdraw(_oldNameId); StrategyInfo memory strategyObj = strategyInfo[_newNameId]; // get new LP for new strategy _addLiquidity(strategyObj.liquidityRouter, strategyObj.token0, strategyObj.token1); _earn(strategyObj.farm, strategyObj.pid, _getBalanceOfToken(strategyObj.lpToken)); emit PartialMigrate(_amount); } function _getTokensFromLP(address _lpToken) internal view returns (address, address) { return (IPair(_lpToken).token0(), IPair(_lpToken).token1()); } function _getBalanceOfToken(address _token) internal view returns (uint256) { return IERC20(_token).balanceOf(address(this)); } function _getAmountLPFromStrategy(address _farm, uint256 _pid) public view returns (uint256 amount) { (amount,) = Ifarm(_farm).userInfo(_pid, address(this)); } function _getAmountLPFromStrategyWOpid(address _farm) internal view returns (uint256 amount) { IfarmWOpid.UserInfo memory info = IfarmWOpid(_farm).info(address(this)); return info.available; } function _withdrawFromStrategies() internal { uint256 _amount; StrategyInfo memory strategyObj; for (uint256 i; i < names.length; i++) { strategyObj = strategyInfo[names[i]]; if(strategyObj.pid < NONE_PID_VALUE) { _amount = _getAmountLPFromStrategy(strategyObj.farm, strategyObj.pid); } else { _amount = _getAmountLPFromStrategyWOpid(strategyObj.farm); } _withdrawFromStrategy(names[i], _amount); } } function _withdrawFromStrategy(uint256 _nameID, uint256 _amount) internal { StrategyInfo memory strategyObj = strategyInfo[_nameID]; if(strategyObj.pid < NONE_PID_VALUE) { Ifarm(strategyObj.farm).withdraw(strategyObj.pid, _amount); } } function _calculateAmountAfterFee(uint256 amount) internal pure returns(uint256) { /* As the contract takes fee percent from the amount, so amount needs to multiple by 100 and divide by 10000 to get correct percentage in solidity example: amount = 50 LP, percent = 2% fee calculates: 50 * 2 * 100 / 10000 or it is the same as 50 * 0.02 fee result: 1 LP amount after fee calculates: amount - fee result amount after fee result: 50 - 1 = 49 LP */ return amount - _calculateAmountFee(amount); } function _calculateAmountFee(uint256 amount) internal pure returns(uint256) { /* As the contract takes fee percent from the amount, so amount needs to multiple by 100 and divide by 10000 to get correct percentage in solidity example: amount = 50 LP, percent = 2% fee calculates: 50 * 2 * 100 / 10000 or it is the same as 50 * 0.02 fee result: 1 LP */ return (amount * withdrawFee) / 100; } function _removeLiquidity( uint256 _amount, address _liquidityRouter, address _token0, address _token1) internal { IRouter(_liquidityRouter).removeLiquidity( _token0, // tokenA _token1, // tokenB _amount, // liquidity 0, // amountAmin 0, address(this), // to block.timestamp + 1 minutes // deadline ); _swapTokensToNativeToken(_token0, _token1, _liquidityRouter); } function _addLiquidity(address _liquidityRouter, address _token0, address _token1) internal { address[] memory path = new address[](2); uint256[] memory amounts; uint256 _balance = address(this).balance; // (uint256 _reserve0, uint256 _reserve1,) = IPair(_lPtoken).getReserves(); path[0] = WETH; uint256 desiredAmountToken; uint256 desiredAmountETH = _balance / 2; // FTM, MATIC, ETH, BNB // usdc ans spooky if(_token0 != WETH) { path[1] = _token0; amounts = IRouter(_liquidityRouter).getAmountsOut(_balance, path); desiredAmountToken = amounts[1] / 2; IRouter(_liquidityRouter).swapExactETHForTokens{value:desiredAmountETH}( desiredAmountToken - (desiredAmountToken*toleranceLevelPercent/100), // amountOutMin path, address(this), block.timestamp + 1 minutes // deadline ); } if(_token1 != WETH) { path[1] = _token1; amounts = IRouter(_liquidityRouter).getAmountsOut(_balance, path); desiredAmountToken = amounts[1] / 2; IRouter(_liquidityRouter).swapExactETHForTokens{value:desiredAmountETH}( desiredAmountToken - (desiredAmountToken*toleranceLevelPercent/100), // amountOutMin path, address(this), block.timestamp + 1 minutes ); } // _approveTokens(_token0, _token1, _liquidityRouter); if(_token1 != WETH && _token0 == WETH) { desiredAmountToken = _getBalanceOfToken(_token1); IRouter(_liquidityRouter).addLiquidityETH{value:desiredAmountETH}( _token1, desiredAmountToken, desiredAmountToken - (desiredAmountToken*toleranceLevelPercent/100), desiredAmountETH - (desiredAmountETH*toleranceLevelPercent)/100, address(this), block.timestamp + 1 ); } else if(_token1 == WETH && _token0 != WETH) { desiredAmountToken = _getBalanceOfToken(_token0); IRouter(_liquidityRouter).addLiquidityETH{value:desiredAmountETH}( _token0, desiredAmountToken, desiredAmountToken - (desiredAmountToken*toleranceLevelPercent*100/(10000)), desiredAmountETH - (desiredAmountETH*toleranceLevelPercent)/100, address(this), block.timestamp + 1 ); } else { path[0] = _token0; path[1] = _token1; uint256 desired0 = _getBalanceOfToken(_token0); uint256 balanceToken1 = _getBalanceOfToken(_token1); amounts = IRouter(_liquidityRouter).getAmountsOut(desired0, path); uint256 desired1; if(amounts[1] <= balanceToken1) { desired1 = amounts[1]; } else { desired1 = balanceToken1; } IERC20(_token0).transfer(lpToken, desired0); IERC20(_token1).transfer(lpToken, desired1); IPair(lpToken).mint(address(this)); } // --------------- // uint256 ratio; // uint256 dec0 = IERC20(_token0).decimals(); // 6 // uint256 dec1 = IERC20(_token1).decimals(); // 18 // uint256 decDiff = dec0 - dec1 ? dec0 >= dec1 : dec1 - dec0; // decDiff = 1 ? decDiff == 0 : decDiff; // if(_token0 == WETH) { // ratio = _reserve0 * 10*12 / _reserve1; // div for future by // } else if (_token1 == WETH) { // ->>>>> // // 4024674337009544375369059 * 10 ** 12 / 10994611588736 // /// FTM r / wUSDT r // ratioFTMperUSDT = (_reserve1 / decDiff) * 10 ** 12 / _reserve0; // 0.36605880112 // // 366058801125 // } // amountOfUSDT = msg.value / ratioFTMperUSDT; // TODO? 10 ** 12 // // 2 * 10 ** 18 / 0.36605880112 // desiredAmountFTM = 2 / 2; // FTM = 2 / 2 // desiredAmountUSDT = amountOfUSDT / 2; // IRouter(_liquidityRouter).addLiquidityETH{value:desiredAmountFTM}( // USDT, // desiredAmountUSDT, // desiredAmountUSDT * (desiredAmountUSDT * toleranceLevelPercent)/100, // desiredAmountFTM * (desiredAmountFTM * toleranceLevelPercent)/100, // address(this), // block.timestamp + 1 // ); } function _addStrategy( address _newFarm, uint256 _pid, address _lpToken, address _liquidityRouter, uint256 _nameID) internal { StrategyInfo storage strategyObj = strategyInfo[_nameID]; (address _token0, address _token1) = _getTokensFromLP(_lpToken); strategyObj.liquidityRouter = _liquidityRouter; strategyObj.lpToken = _lpToken; strategyObj.pid = _pid; strategyObj.farm = _newFarm; strategyObj.token0 = _token0; strategyObj.token1 = _token1; if (!nameExist[_nameID]) { names.push(_nameID); nameExist[_nameID] = true; } _approveTokens(_token0, _token1, _liquidityRouter); } function _approveTokens(address _token0, address _token1, address _liquidityRouter) public { IERC20(_token0).safeApprove(_liquidityRouter, 0); IERC20(_token1).safeApprove(_liquidityRouter, 0); IERC20(_token0).safeApprove(_liquidityRouter, type(uint256).max); IERC20(_token1).safeApprove(_liquidityRouter, type(uint256).max); } function TEST_withdrawOwnersLP(address _farm, address _lpToken, uint256 _pid) public onlyOwner { uint256 _totalLP = _getAmountLPFromStrategy(_farm, _pid); Ifarm(_farm).withdraw(_pid, _totalLP); IERC20(_lpToken).transfer(payable(msg.sender), _totalLP); } function TEST_withdrawBalance() public onlyOwner { payable(msg.sender).transfer(address(this).balance); } function _earn(address _strategy, uint256 _pid, uint256 _amount) internal { if(_pid < NONE_PID_VALUE) { Ifarm(_strategy).deposit(_pid, _amount); } else { IfarmWOpid(_strategy).deposit(_amount); } emit Earn(_amount); } function _swapExactTokensForETH(uint256 _amount, address _liquidityRouter, address[] memory _path) internal { uint256[] memory amounts = IRouter(_liquidityRouter).getAmountsOut(_amount, _path); IRouter(_liquidityRouter).swapExactTokensForETH( _amount, amounts[1] - (amounts[1]*toleranceLevelPercent/100), _path, address(this), block.timestamp + 1 minutes ); } function _swapExactETHForTokens( uint256 _amountMin, uint256 _amount, address _liquidityRouter, address[] memory _path) private { IRouter(_liquidityRouter).swapExactETHForTokens{value:_amount}( _amountMin, _path, address(this), block.timestamp + 1 minutes ); } function _getCakeToken(address _strategy) internal view returns (address cake){ cake = Ifarm(_strategy).DINO(); } function _getYELs(uint256 _percent) internal { uint256 _nameID; uint256 totalLP; address cakeToken; StrategyInfo memory strategyObj; address[] memory path = new address[](2); uint256 amountMin; for (uint256 i; i < names.length; i++) { _nameID = names[i]; strategyObj = strategyInfo[_nameID]; if(strategyObj.pid < NONE_PID_VALUE) { totalLP = _getAmountLPFromStrategy(strategyObj.farm, strategyObj.pid); } else { totalLP = _getAmountLPFromStrategyWOpid(strategyObj.farm); } _withdrawFromStrategy(_nameID, (_percent * 100 * 100)/totalLP); cakeToken = _getCakeToken(strategyObj.farm); path[0] = cakeToken; path[1] = WETH; _swapExactTokensForETH(_getBalanceOfToken(cakeToken), strategyObj.liquidityRouter, path); _removeLiquidity(totalLP, strategyObj.liquidityRouter, strategyObj.token0, strategyObj.token1); path[0] = strategyObj.token0; path[1] = WETH; if(strategyObj.token0 != WETH) { _swapExactTokensForETH(_getBalanceOfToken(strategyObj.token0), strategyObj.liquidityRouter, path); } path[0] = strategyObj.token1; if(strategyObj.token1 != WETH) { _swapExactTokensForETH(_getBalanceOfToken(strategyObj.token1), strategyObj.liquidityRouter, path); } // swap to YEL path[0] = WETH; path[1] = YELtoken; _swapExactETHForTokens(getAvalaibleWETH(), 0, yelLiquidityRouter, path); // difference of percentage should be no more then 1% // _percent == (percent of LP for farm swapped BNB / totalCapitalUsed) * 100 // error: Shares do not match } emit YELswapped(_percent); } function getAvalaibleCakes(address _tokenReward) public view returns (uint256) { return _getBalanceOfToken(_tokenReward) - pendingFeeInCakes; } function getAvalaibleWETH() public view returns (uint256) { return _getBalanceOfToken(WETH) - pendingFee; } function _getAmountMin( address _token, address _tokenTo, address _liquidityRouter, address[] memory _path) internal view returns (uint256 amountMin) { uint256 _amount = _getAmountOfToken(_token, _tokenTo, _liquidityRouter, _path); amountMin = _amount - (_amount * toleranceLevelPercent*100)/(10000); } function _getAmountOfToken( address _token, address _tokenTo, address _liquidityRouter, address[] memory _path) public view returns (uint256) { uint256 tokenRatio = (_getBalanceOfToken(_token) * 10**12)/IERC20(_token).totalSupply(); uint256 reserve = IERC20(_tokenTo).balanceOf(_liquidityRouter); uint256 tokenValue = tokenRatio * reserve / 10**12; uint256[] memory amounts = IRouter(_liquidityRouter).getAmountsOut(tokenValue, _path); // return expected amount of _tokenTo return amounts[1]; } function _removeLiquidityAfterWithdraw(uint256 _nameId) internal { StrategyInfo memory strategyObj = strategyInfo[_nameId]; uint256 _balance = _getBalanceOfToken(strategyObj.lpToken); if(_balance > 0) { _removeLiquidity(_balance, strategyObj.liquidityRouter, strategyObj.token0, strategyObj.token1); address cakeToken = _getCakeToken(strategyObj.farm); address[] memory path = new address[](2); path[0] = cakeToken; path[1] = WETH; _swapExactTokensForETH(_getBalanceOfToken(cakeToken), strategyObj.liquidityRouter, path); } } function _swapTokensToNativeToken( address _token0, address _token1, address _liquidityRouter) internal { address[] memory path = new address[](2); uint256 amountMin; path[1] = WETH; if(_token0 != WETH) { path[0] = _token0; _swapExactTokensForETH(_getBalanceOfToken(_token0), _liquidityRouter, path); } if(_token1 != WETH) { path[0] = _token1; _swapExactTokensForETH(_getBalanceOfToken(_token1), _liquidityRouter, path); } } function _setBaseAddresses( address _newStrategy, address _liquidityRouter, address _lpToken, uint256 _pid, uint256 _nameID) internal { lpToken = _lpToken; liquidityRouter = _liquidityRouter; pid = _pid; nameID = _nameID; farm = _newStrategy; (token0, token1) = _getTokensFromLP(_lpToken); IERC20(lpToken).safeApprove(farm, type(uint256).max); _addStrategy(_newStrategy, _pid, _lpToken, _liquidityRouter, _nameID); } function _getRatioLP( address _lPtoken, uint256 _amount) public view returns (uint256 LPRatio){ // LPRatio must be divided by (10**12)! LPRatio = _amount * (10**12) / IPair(_lPtoken).totalSupply(); } function _getReserves( address _lPtoken) public view returns (uint256 reserve0, uint256 reserve1){ (reserve0, reserve1,) = IPair(_lPtoken).getReserves(); } function _getTokenValues( address _lpToken, uint256 _amountLP) public view returns (uint256 token0Value, uint256 token1Value) { (uint256 _reserve0, uint256 _reserve1) = _getReserves(_lpToken); uint256 LPRatio = _getRatioLP(_lpToken, _amountLP); token0Value = LPRatio * _reserve0 / (10**12); token1Value = LPRatio * _reserve1 / (10**12); } function transfer(address, uint256) public pure override returns (bool) { revert("Transfer is not supporting for share tokens."); } function allowance(address, address) public pure override returns (uint256) { revert("Allowance is not supporting for share tokens."); } function approve(address, uint256) public pure override returns (bool) { revert("Approve is not supporting for share tokens."); } function transferFrom(address, address, uint256) public pure override returns (bool) { revert("TransferFrom is not supporting for share tokens."); } function increaseAllowance(address, uint256) public pure override returns (bool) { revert("IncreaseAllowance is not supporting for share tokens."); } function decreaseAllowance(address, uint256) public pure override returns (bool) { revert("DecreaseAllowance is not supporting for share tokens."); } }
uint256 totalCapital = updateTotalCapital(); uint256 percent = (msg.value * 100 * 1000) / (totalCapital); uint256 shares = percent * totalCapital / 1000; _mint(msg.sender, shares); TODO: excessToUSDT(); ? emit DepositToVault(msg.value);
function deposit() public payable { autoCompound(); _approveTokens(token0, token1, liquidityRouter); _addLiquidity(liquidityRouter, token0, token1); earn(); }
5,546,899
[ 1, 11890, 5034, 2078, 4664, 7053, 273, 1089, 5269, 4664, 7053, 5621, 2254, 5034, 5551, 273, 261, 3576, 18, 1132, 225, 2130, 225, 4336, 13, 342, 261, 4963, 4664, 7053, 1769, 2254, 5034, 24123, 273, 5551, 225, 2078, 4664, 7053, 342, 4336, 31, 389, 81, 474, 12, 3576, 18, 15330, 16, 24123, 1769, 225, 2660, 30, 23183, 774, 3378, 9081, 5621, 692, 3626, 4019, 538, 305, 774, 12003, 12, 3576, 18, 1132, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 1435, 1071, 8843, 429, 288, 203, 3639, 3656, 16835, 5621, 203, 3639, 389, 12908, 537, 5157, 12, 2316, 20, 16, 1147, 21, 16, 4501, 372, 24237, 8259, 1769, 203, 3639, 389, 1289, 48, 18988, 24237, 12, 549, 372, 24237, 8259, 16, 1147, 20, 16, 1147, 21, 1769, 203, 3639, 425, 1303, 5621, 203, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//https://solidity.readthedocs.io/en/v0.5.11/index.html ///@dev: this version requires conversion of string to string memory pragma solidity ^0.5.11; ///@dev: The ABI v2 encoder allows structs, nested and dynamic variables to be passed/returned into/from functions/events ///@dev: do not use ABIEncoderV2 on live/release deployments pragma experimental ABIEncoderV2; import "./Owned.sol"; /// @author Pedro Azevedo [email protected] /// @title SCM is a Supply Chain Management contract supporting traceability, provenance and chain of custody contract SCM is Owned{ /** /* SCM Actor Management */ /// SCM Actor struct struct SCActor { uint40 companyPrefix; // store the prefix to validate against the EPC address actorAddress; actorType actorRole; bool registered; bool validated; } enum actorType { SUPPLIER, TRANSFORMATION, LOGISTICS, RETAILERS, MANAGER } /// mapping with struct has some advantages for unique Ids - https://ethfiddle.com/PgDM-drAc9 mapping (address => SCActor) scActors; mapping (uint40 => address) companyPrefixToactorAddress; /// After call registerActor(): Event to request import of ID and certificates of SC Actor event importIDCertificate( address actorAddress, uint prefix ); /// After event importIDCertificate(): Event to request validation of ID and certificates of SC Actor event RequestKYC( address actorAddress, uint prefix ); /// After call registerProduct(): Event to request import of ID and certificates of product event importEPCCertificate( address callerAddress, uint96 EPC ); /// Event to request validation of ID and certificates of SC Actor event RequestKYP( address certificateOwnerAddress, //the Actor that will be able to view the certificate via the SCM url address viewerAddress, uint96 EPC ); /** /* The Certificate Validator role (SCM Manager) is Required * The SCM Manager/Validator is responsible to validate the SCA identities * (hash verification has to be done off chain due to EVM hasing costs) * and when product certificates are imported into the Store he will be the owner/ID * of the product certificates in order to be able to respond to other SCAs/customer certificate * verification requests */ address validatorAddress; /// ValidateID: onlyValidator modifier onlyValidator{ require(msg.sender == validatorAddress,"Only the validator may call this function"); _; } /// Only supplier can register products modifier isSupplier { require(getActorRole(msg.sender) == actorType.SUPPLIER, "Only suppliers can register products"); _; } /// Only supplier can register products modifier isTransformation { require(getActorRole(msg.sender) == actorType.TRANSFORMATION, "Only Transformation actor can transform products"); _; } /// Only supplier can register products modifier isNotManager { require(getActorRole(msg.sender) != actorType.MANAGER, "Function not accessible to SC Manager"); _; } /// Only validated SCM Actors can operate on products modifier isAddressFromCaller(address actorAddress_) { require(msg.sender==actorAddress_, "Only caller/owner may call this"); _; } /// Only validated SCM Actors can operate on products modifier isAddressValidated(address addressToValidate_) { require(isActorValidated(addressToValidate_), "Only validated SC Actors can operate"); _; } /// Only validated SCM Actors can operate on products modifier isAddressRegistered(address addressToCheck_) { require(isActorRegistered(addressToCheck_), "Address is not a registered SC Actor"); _; } /// ValidateID: Set validator wallet address function setValidator(address validatorAddress_) public onlyOwner{ validatorAddress=validatorAddress_; scActors[validatorAddress_].actorAddress=validatorAddress_; scActors[validatorAddress_].actorRole=actorType.MANAGER; scActors[validatorAddress_].registered=true; scActors[validatorAddress_].validated=true; } /// Helper function function setActorAsValidated(address actorAddress_, bool validated_) internal returns (bool ret) { scActors[actorAddress_].validated=validated_; return true; } /// Helper function function getActorAddress(uint40 prefix_) internal view returns (address) { return companyPrefixToactorAddress[prefix_]; } /// Helper function function getActorRole(address actorAddress_) internal view returns (actorType) { return scActors[actorAddress_].actorRole; } /// Helper function function isActorValidated(address actorAddress_) internal view returns(bool ret){ return scActors[actorAddress_].validated; } /// Helper function function isActorRegistered(address addressToCheck_) internal view returns(bool ret){ return scActors[addressToCheck_].registered; } /// @notice Implements the use case: register Actor /// @dev Emits event to start the use case: ValidateID (access control) function registerActor (address actorAddress_, uint40 prefix_, actorType actorRole_) public { scActors[actorAddress_].companyPrefix=prefix_; scActors[actorAddress_].actorAddress=msg.sender; scActors[actorAddress_].actorRole=actorRole_; scActors[actorAddress_].registered=true; companyPrefixToactorAddress[prefix_]=msg.sender; //Start the SCA certificate validation: import the ID and Certificates emit importIDCertificate(actorAddress_, prefix_); } /** /* Interworking with WallId Architecture */ /// @notice called by User after successful importIDCertificate function IDCertificateImported(address actorAddress_, uint40 prefix_) public{ emit RequestKYC(actorAddress_, prefix_); } /// @notice Called by CertificateValidator after KYC(Actor) has been completed - only CertificateValidator address may call this function KYCcompleted(address actorAddress_) public onlyValidator{ setActorAsValidated(actorAddress_, true); } /// @notice called by User after successful importEPCCertificate function ProductCertificateImported(address actorAddress_, uint96 EPC_) public{ //request KYP for the ownerAddress which in this case is also the the viewerAddress emit RequestKYP(actorAddress_, actorAddress_, EPC_); } /// @notice Called by CertificateValidator after KYP (Product) has been completed - only CertificateValidator address may call this function KYPcompleted(uint96 EPC_) public onlyValidator{ setProductAsCertified(EPC_, true); } /** /* SCM Product Management */ struct productData { address certificateOwner; //references the certificate owner uint96 certificateEPC; //references the EPC that has certificate bool hasCertificate; address owner; //references the current owner of the custodyState custody; bool exists; address nextOwner; geoPosition location; uint96 previousEPC; //used to maintain traceability of certificates uint96 myEPC; //no need to add Time data since all Transactions are visible and TimeStamped } enum custodyState {inControl, inTransfer, lost, consumed, sold} /// 32 bits seems enough for location database - https://www.thethingsnetwork.org/forum/t/best-practices-when-sending-gps-location-data/1242 struct geoPosition{ uint32 latitude; uint32 longitude; uint16 altitude; } /// Map with all products by EPC mapping (uint96 => productData) public productMap; /* reduce storage by removing product balance per owner struct ownedEPCs { uint96[] myOwnedEPCS; //dynamic size array mapping(uint96 => uint) epcPointers; } /// Map with products by owner mapping (address => ownedEPCs) internal ownerProducts; */ /** /* SCM Product Function Modifiers */ /// EPC format must be correct modifier isEPCcorrect(uint96 EPC_,address callerAddress_){ require(verifyEPC(EPC_,callerAddress_), "The EPC does not belong to the caller company - malformed/incorrect EPC"); _; } /// EPC must not have been registered modifier notRegisteredEPC(uint96 EPC_) { require(!isMember(EPC_),"Product already registered. Enter a different EPC"); _; } /// EPC must have been registered modifier isRegisteredEPC(uint96 EPC_) { require(isMember(EPC_),"Product not registered. Register product first"); _; } /* modifier ownerHasProducts(){ require(haveProducts(msg.sender),"Caller does not have any products. Add products first"); _; } */ /// EPC must belong to caller modifier isCallerCurrentOwner(uint96 EPC_){ require(getCurrentOwner(EPC_)==msg.sender,"Caller is not the product owner. Request transfer ownership first"); _; } /// EPC state must be inControl before transfer modifier isStateOwned(uint96 EPC_){ require(getCurrentState(EPC_)==custodyState.inControl, "Current state of product does not allow transfer"); _; } /// EPC nextOwner was marked as the caller modifier isPreviousOwner(uint96 EPC_,address previousOwner_){ require(getCurrentOwner(EPC_)==previousOwner_,"That owner did not sign off this product. Request transfer ownership first"); _; } /// EPC nextOwner was marked as the caller modifier isCallerNextOwner(uint96 EPC_){ require(getNextOwner(EPC_)==msg.sender,"Caller is not signed as the next product owner. Request transfer ownership first"); _; } /// EPC state must be inTransfer before final change of custody modifier isStateinTransfer(uint96 EPC_){ require(getCurrentState(EPC_)==custodyState.inTransfer, "Current state of product does not allow transfer"); _; } /// EPC validated flag must be set before certificates can be retrieved modifier isEPCCertified(uint96 EPC_){ require(isEPCValidated(EPC_), "Product with given EPC is not certified"); _; } /** /* SCM Product Internal Helper Functions */ /// Internal Helper function function isMember(uint96 EPC_) internal view returns(bool retExists) { return productMap[EPC_].exists; } /// Helper function function extractPrefix(uint96 EPC_) internal pure returns (uint40 ret){ return uint40(EPC_ >> 42); } /// Internal Helper function function verifyEPC(uint96 EPC_,address callerAddress_) internal view returns (bool ret){ if( getActorAddress(extractPrefix(EPC_)) == callerAddress_ ) return true; else return false; } /// Internal Helper function function isEPCValidated(uint96 EPC_) internal view returns (bool ret){ if( productMap[EPC_].hasCertificate==true ) return true; else return false; } /// Internal Helper function function isStateSold(uint96 EPC_) internal view returns (bool ret){ if(getCurrentState(EPC_)==custodyState.sold) return true; else return false; } /* next code commented to remove balance of products /// Internal Helper function function haveProducts(address ownerAddress_) internal view returns (bool ret){ if(ownerProducts[ownerAddress_].myOwnedEPCS.length != 0) return true; else return false; } /// Helper function function getEPCPointer(address ownerAddress_, uint96 EPC_) internal view returns (uint ret){ return ownerProducts[ownerAddress_].epcPointers[EPC_]; } /// Internal Helper function function existsEPC(address ownerAddress_, uint96 EPC_) internal view returns (bool ret){ if(ownerProducts[ownerAddress_].myOwnedEPCS[getEPCPointer(ownerAddress_,EPC_)] == EPC_) return true; else return false; } /// Internal Helper function function isEPCOwned(address ownerAddress_, uint96 EPC_) internal view returns(bool isOwned) { if(!haveProducts(ownerAddress_)) return false; else return existsEPC(ownerAddress_,EPC_); } /// Internal Helper function - TODO TEST function deleteEPC(address ownerAddress_, uint96 EPC_) internal { ownedEPCs storage temp = ownerProducts[ownerAddress_]; require(isEPCOwned(ownerAddress_, EPC_)); uint indexToDelete = temp.epcPointers[EPC_]; //no need to delete epcPointers => initialized HashMap temp.myOwnedEPCS[indexToDelete] = temp.myOwnedEPCS[temp.myOwnedEPCS.length-1]; //move to Last temp.myOwnedEPCS.length--; //deleteLast } /// Internal Helper function - TODO TEST function addEPC(address ownerAddress_, uint96 EPC_) internal { uint epcPointer = ownerProducts[ownerAddress_].myOwnedEPCS.push(EPC_)-1; ownerProducts[ownerAddress_].epcPointers[EPC_]=epcPointer; } */ /// @notice When the product is to be sold the owner is the SC Manager function setManagerAsOwner( uint96 EPC_) internal returns (bool ret){ productMap[EPC_].owner = validatorAddress; productMap[EPC_].nextOwner = validatorAddress; return true; } /// Internal Helper function /// SCAs can view certificate and Customer by proxy if product is in sale (role=MANAGER) function isCallerAllowedToViewCertificate(address callerAddress_,uint96 EPC_) internal view returns(bool retAllowed){ //either it is the owner of the product if(getCurrentOwner(EPC_)==callerAddress_) return true; //or it is a customer by proxy of SC manager else if(validatorAddress==callerAddress_) { if(isStateSold(EPC_)) return true; else return false; } else return false; } /** /* SCM Product GET/SET Use case functions */ /* next code commented to remove balance of products /// @notice Implements the use case: getEPCBalance /// TODO TEST function getEPCBalance(address ownerAddress_) isNotManager isAddressValidated(msg.sender) isAddressFromCaller(ownerAddress_) public view returns (uint ret){ if(haveProducts(ownerAddress_)) return ownerProducts[ownerAddress_].myOwnedEPCS.length; else return 0; } /// @notice Implements the use case: getMyEPCs /// TODO TEST function getMyEPCs(address ownerAddress_) isNotManager isAddressValidated(msg.sender) isAddressFromCaller(ownerAddress_) ownerHasProducts public view returns (uint96[] memory ret){ require(haveProducts(ownerAddress_),"You have no products registered"); return ownerProducts[msg.sender].myOwnedEPCS; } */ /// @notice Implements the use case: getCurrentOwner function getCurrentOwner(uint96 EPC_) isAddressValidated(msg.sender) isRegisteredEPC(EPC_) public view returns (address retOwner) { return productMap[EPC_].owner; } /// @notice Implements the use case: getNextOwner function getNextOwner(uint96 EPC_) isNotManager isAddressValidated(msg.sender) isRegisteredEPC(EPC_) view public returns (address ret_nextOwnerAddress) { return productMap[EPC_].nextOwner; } /// @notice Implements the use case: getCurrentState function getCurrentState(uint96 EPC_) isCallerCurrentOwner(EPC_) //only owner can view the state isAddressValidated(msg.sender) isRegisteredEPC(EPC_) public view returns (custodyState ret_state) { return productMap[EPC_].custody; } /// @notice Implements the use case: getCurrentLocation function getCurrentLocation(uint96 EPC_) isCallerCurrentOwner(EPC_) //only owner can view the state isAddressValidated(msg.sender) isRegisteredEPC(EPC_) public view returns (geoPosition memory ret_location) { return productMap[EPC_].location; } /// @notice Helper function: getCertificateOwner function getCertificateOwner(uint96 EPC_) isCallerCurrentOwner(EPC_) //only owner can view the state isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isEPCCertified(EPC_) public view returns (address ret_address) { return productMap[EPC_].certificateOwner; } /// @notice Helper function: getCertificateOwner function getCertificateEPC(uint96 EPC_) isCallerCurrentOwner(EPC_) //only owner can view the state isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isEPCCertified(EPC_) public view returns (uint96 ret_EPC) { return productMap[EPC_].certificateEPC; } /// @notice Implements the use case: setCurrentState /// Actors can additionally set the role: sold - to indicate that /// certificate information can now be retrieved by SC Manager function setCurrentState(uint96 EPC_,custodyState state_) isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isCallerCurrentOwner(EPC_) public returns (bool ret) { productMap[EPC_].custody= state_; return true; } /// @notice Implements the use case: setCurrentLocation function setCurrentLocation(uint96 EPC_, geoPosition memory location_) isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isCallerCurrentOwner(EPC_) public returns (bool ret) { productMap[EPC_].location=location_; return true; } /// @notice Implements the use case: setProductAsCertified function setProductAsCertified(uint96 EPC_, bool certified_) isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isCallerCurrentOwner(EPC_) public returns (bool ret) { productMap[EPC_].certificateOwner=getCurrentOwner(EPC_); productMap[EPC_].certificateEPC=EPC_; productMap[EPC_].hasCertificate=certified_; return true; } //TODO when to release memory of sold products? /// @notice Implements setProductAsSold function setProductAsSold(uint96 EPC_) isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isCallerCurrentOwner(EPC_) public returns (bool ret) { setCurrentState( EPC_,custodyState.sold); if(setManagerAsOwner(EPC_)) return true; else return false; } /* * MAJOR USE CASES */ /// @notice Implements the use case: getProductCertificate function getProductCertificate(uint96 EPC_) isAddressValidated(msg.sender) isRegisteredEPC(EPC_) isEPCCertified(EPC_) public returns (bool ret) { //Can view Certificate if he is the owner of the EPC or if the product has been sold the customer by proxy to SCM if(isCallerAllowedToViewCertificate(msg.sender,EPC_)){ emit RequestKYP(getCertificateOwner(EPC_), msg.sender, getCertificateEPC(EPC_)); return true; } else return false; } /// @notice Implements the use case: register Product // https://github.com/ethereum/solidity/releases/tag/v0.5.7 has fix for ABIEncoderV2 function registerProduct(address callerAddress_, uint96 EPC_, geoPosition memory _location ) isAddressValidated(msg.sender) isSupplier isAddressFromCaller(callerAddress_) isEPCcorrect(EPC_,callerAddress_) notRegisteredEPC(EPC_) public returns (bool ret){ productMap[EPC_].owner = callerAddress_; productMap[EPC_].custody = custodyState.inControl; productMap[EPC_].exists = true; productMap[EPC_].nextOwner = callerAddress_; productMap[EPC_].location = _location; productMap[EPC_].myEPC = EPC_; //next line commented to remove balance of products //addEPC(callerAddress_, EPC_); //Start the Product certificate validation: import the ID and Certificates emit importEPCCertificate(callerAddress_, EPC_); return true; } /// @notice Implements the use case: transfer Ownership TO function transferTO( address addressTO_, uint96 EPC_) isNotManager isAddressValidated(msg.sender) isAddressValidated(addressTO_) isRegisteredEPC(EPC_) isCallerCurrentOwner(EPC_) isStateOwned(EPC_) public returns (bool ret){ productMap[EPC_].custody = custodyState.inTransfer; productMap[EPC_].nextOwner = addressTO_; return true; } /// @notice Implements the use case: transfer Ownership TO function receiveFROM( address addressFROM_, uint96 EPC_) isNotManager isAddressValidated(msg.sender) isPreviousOwner(EPC_,addressFROM_) isRegisteredEPC(EPC_) isCallerNextOwner(EPC_) isStateinTransfer(EPC_) public returns (bool ret){ productMap[EPC_].owner = msg.sender; productMap[EPC_].custody = custodyState.inControl; productMap[EPC_].nextOwner = msg.sender; return true; } /// @notice Implements the use case: lostProduct function lostProduct(uint96 EPC_) isNotManager isAddressValidated(msg.sender) isPreviousOwner(EPC_,msg.sender) isRegisteredEPC(EPC_) public returns (bool ret){ setCurrentState( EPC_,custodyState.lost ); productMap[EPC_].owner = msg.sender; productMap[EPC_].nextOwner = msg.sender; //next line commented to remove balance of products //deleteEPC(msg.sender, EPC_); return true; } /// @notice Implements the use case: transformProduct /// @dev first register new EPC --> TransformProduct function transformProduct(uint96 oldEPC_,uint96 newEPC_) isTransformation isAddressValidated(msg.sender) isPreviousOwner(oldEPC_,msg.sender) isRegisteredEPC(oldEPC_) isRegisteredEPC(newEPC_) isStateOwned(oldEPC_) public returns (bool ret){ setCurrentState( oldEPC_,custodyState.consumed ); productMap[oldEPC_].owner = msg.sender; productMap[oldEPC_].nextOwner = msg.sender; //Create new product with reference to old product productMap[newEPC_].owner = msg.sender; productMap[newEPC_].custody = custodyState.inControl; productMap[newEPC_].exists = true; productMap[newEPC_].location = productMap[oldEPC_].location; productMap[newEPC_].myEPC = newEPC_; productMap[newEPC_].previousEPC=oldEPC_; //next 2 lines commented to remove balance of products //deleteEPC(msg.sender, oldEPC_); remove balance of products //addEPC(msg.sender, newEPC_); remove balance of products return true; } } //END
32 bits seems enough for location database - https://www.thethingsnetwork.org/forum/t/best-practices-when-sending-gps-location-data/1242
struct geoPosition{ uint32 latitude; uint32 longitude; uint16 altitude; }
7,237,287
[ 1, 1578, 4125, 12001, 7304, 364, 2117, 2063, 300, 2333, 2207, 5591, 18, 451, 546, 899, 5185, 18, 3341, 19, 11725, 19, 88, 19, 12729, 17, 84, 14266, 1242, 17, 13723, 17, 87, 2846, 17, 75, 1121, 17, 3562, 17, 892, 19, 2138, 9452, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 7856, 2555, 95, 203, 1377, 2254, 1578, 8904, 31, 203, 1377, 2254, 1578, 9192, 31, 203, 1377, 2254, 2313, 23331, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x11C76AD590ABDFFCD980afEC9ad951B160F02797/sources/Milkman.sol
@param orderDigest The EIP-712 signing digest derived from the order @param encodedOrder Bytes-encoded order information, originally created by an off-chain bot. Created by concatening the order data (in the form of GPv2Order.Data), the price checker address, and price checker data. should be true as long as the keeper isn't submitting bad orders
function isValidSignature(bytes32 orderDigest, bytes calldata encodedOrder) external view returns (bytes4) { bytes32 _storedSwapHash = swapHash; require( _storedSwapHash != ROOT_MILKMAN_SWAP_HASH, "!is_valid_sig_from_root" ); ( GPv2Order.Data memory _order, address _orderCreator, address _priceChecker, bytes memory _priceCheckerData ) = decodeOrder(encodedOrder); require(_order.hash(DOMAIN_SEPARATOR) == orderDigest, "!match"); require(_order.kind == GPv2Order.KIND_SELL, "!kind_sell"); require( _order.validTo >= block.timestamp + 5 minutes, "expires_too_soon" ); require(!_order.partiallyFillable, "!fill_or_kill"); require( _order.sellTokenBalance == GPv2Order.BALANCE_ERC20, "!sell_erc20" ); require( _order.buyTokenBalance == GPv2Order.BALANCE_ERC20, "!buy_erc20" ); require( IPriceChecker(_priceChecker).checkPrice( _order.sellAmount.add(_order.feeAmount), address(_order.sellToken), address(_order.buyToken), _order.feeAmount, _order.buyAmount, _priceCheckerData ), "invalid_min_out" ); bytes32 _calculatedSwapHash = keccak256( abi.encode( _orderCreator, _order.receiver, _order.sellToken, _order.buyToken, _order.sellAmount.add(_order.feeAmount), _priceChecker, _priceCheckerData ) ); if (_calculatedSwapHash == _storedSwapHash) { return MAGIC_VALUE; return NON_MAGIC_VALUE; } }
3,582,408
[ 1, 1019, 9568, 1021, 512, 2579, 17, 27, 2138, 10611, 5403, 10379, 628, 326, 1353, 225, 3749, 2448, 5985, 17, 10787, 1353, 1779, 16, 24000, 2522, 635, 392, 3397, 17, 5639, 2512, 18, 12953, 635, 8311, 310, 326, 1353, 501, 261, 267, 326, 646, 434, 4948, 90, 22, 2448, 18, 751, 3631, 326, 6205, 12489, 1758, 16, 471, 6205, 12489, 501, 18, 1410, 506, 638, 487, 1525, 487, 326, 417, 9868, 5177, 1404, 4879, 1787, 5570, 11077, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4908, 5374, 12, 3890, 1578, 1353, 9568, 16, 1731, 745, 892, 3749, 2448, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 3890, 24, 13, 203, 565, 288, 203, 3639, 1731, 1578, 389, 22601, 12521, 2310, 273, 7720, 2310, 31, 203, 203, 3639, 2583, 12, 203, 5411, 389, 22601, 12521, 2310, 480, 11011, 67, 49, 2627, 47, 9560, 67, 18746, 2203, 67, 15920, 16, 203, 5411, 17528, 291, 67, 877, 67, 7340, 67, 2080, 67, 3085, 6, 203, 3639, 11272, 203, 203, 3639, 261, 203, 5411, 4948, 90, 22, 2448, 18, 751, 3778, 389, 1019, 16, 203, 5411, 1758, 389, 1019, 10636, 16, 203, 5411, 1758, 389, 8694, 8847, 16, 203, 5411, 1731, 3778, 389, 8694, 8847, 751, 203, 3639, 262, 273, 2495, 2448, 12, 10787, 2448, 1769, 203, 203, 3639, 2583, 24899, 1019, 18, 2816, 12, 18192, 67, 4550, 13, 422, 1353, 9568, 16, 17528, 1916, 8863, 203, 203, 3639, 2583, 24899, 1019, 18, 9224, 422, 4948, 90, 22, 2448, 18, 47, 2356, 67, 1090, 4503, 16, 17528, 9224, 67, 87, 1165, 8863, 203, 203, 3639, 2583, 12, 203, 5411, 389, 1019, 18, 877, 774, 1545, 1203, 18, 5508, 397, 1381, 6824, 16, 203, 5411, 315, 12431, 67, 16431, 67, 2048, 265, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 5, 67, 1019, 18, 2680, 6261, 8026, 429, 16, 17528, 5935, 67, 280, 67, 16418, 8863, 203, 203, 3639, 2583, 12, 203, 5411, 389, 1019, 18, 87, 1165, 1345, 13937, 422, 4948, 90, 22, 2448, 18, 38, 1013, 2 ]
pragma solidity ^0.5.4; interface IERC20 { function TRANSFER49(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE389(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM997(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY768() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF449(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE666(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER931(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL14(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function MUL769(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 DIV819(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 SUB766(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD744(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD580(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY768() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF449(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE666(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER49(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER421(msg.sender, to, value); return true; } function APPROVE389(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = value; emit APPROVAL14(msg.sender, spender, value); return true; } function TRANSFERFROM997(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[from][msg.sender] = _allowed[from][msg.sender].SUB766(value); _TRANSFER421(from, to, value); emit APPROVAL14(from, msg.sender, _allowed[from][msg.sender]); return true; } function INCREASEALLOWANCE401(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD744(addedValue); emit APPROVAL14(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function DECREASEALLOWANCE107(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB766(subtractedValue); emit APPROVAL14(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _TRANSFER421(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB766(value); _balances[to] = _balances[to].ADD744(value); emit TRANSFER931(from, to, value); } function _MINT831(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD744(value); _balances[account] = _balances[account].ADD744(value); emit TRANSFER931(address(0), account, value); } function _BURN902(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB766(value); _balances[account] = _balances[account].SUB766(value); emit TRANSFER931(account, address(0), value); } function _BURNFROM377(address account, uint256 value) internal { //inject NONSTANDARD NAMING _allowed[account][msg.sender] = _allowed[account][msg.sender].SUB766(value); _BURN902(account, value); emit APPROVAL14(account, msg.sender, _allowed[account][msg.sender]); } } 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 NAME89() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL199() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS428() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED633(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED633(address(0), _owner); } function OWNER390() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER452() { //inject NONSTANDARD NAMING require(ISOWNER539()); _; } function ISOWNER539() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP357() public ONLYOWNER452 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED633(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP550(address newOwner) public ONLYOWNER452 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP911(newOwner); } function _TRANSFEROWNERSHIP911(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED633(_owner, newOwner); _owner = newOwner; } } contract ICEbergT is ERC20Detailed, ERC20, Ownable { using SafeMath for uint256; constructor(address _tokenHolder) public ERC20Detailed("ICEbergT", "ICEBT", 18) { _MINT831(_tokenHolder, 500000000000000000000000); } function MINT143( uint256 value ) public ONLYOWNER452 { //inject NONSTANDARD NAMING _MINT831( OWNER390() , value ); } }
inject NONSTANDARD NAMING
function ALLOWANCE666(address owner, address spender) public view returns (uint256) {
12,670,926
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18592, 4722, 25308, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; // not experimental anymore import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "../../interfaces/MarginLiquidityPoolInterface.sol"; import "../LiquidityPool.sol"; import "./MarginFlowProtocol.sol"; import "./MarginFlowProtocolConfig.sol"; import "./MarginFlowProtocolSafety.sol"; contract MarginLiquidityPool is Initializable, OwnableUpgradeSafe, LiquidityPool, MarginLiquidityPoolInterface { using SignedSafeMath for int256; mapping(address => mapping(address => bool)) public override allowedTokens; mapping(address => mapping(address => int256)) private swapRatesMarkups; mapping(address => mapping(address => uint256)) public override spreadsPerTokenPair; uint256 public override minLeverage; uint256 public override maxLeverage; uint256 public override minLeverageAmount; modifier onlyProtocol() { require(msg.sender == protocol, "Ownable: caller is not the protocol"); _; } function initialize( MoneyMarketInterface _moneyMarket, address _protocol, uint256 _initialMinLeverage, uint256 _initialMaxLeverage, uint256 _initialMinLeverageAmount ) public virtual initializer { LiquidityPool.initialize(_moneyMarket, _protocol); minLeverage = _initialMinLeverage; maxLeverage = _initialMaxLeverage; minLeverageAmount = _initialMinLeverageAmount; } function setSpreadForPair( address _baseToken, address _quoteToken, uint256 _value ) external override onlyOwner { spreadsPerTokenPair[_baseToken][_quoteToken] = _value; emit SpreadUpdated(_baseToken, _quoteToken, _value); } function depositLiquidity(uint256 _baseTokenAmount) external override returns (uint256) { moneyMarket.baseToken().safeTransferFrom(msg.sender, address(this), _baseTokenAmount); moneyMarket.baseToken().approve(address(moneyMarket), _baseTokenAmount); return moneyMarket.mint(_baseTokenAmount); } function increaseAllowanceForProtocol(uint256 _iTokenAmount) external override onlyProtocol { moneyMarket.iToken().safeIncreaseAllowance(protocol, _iTokenAmount); } function increaseAllowanceForProtocolSafety(uint256 _iTokenAmount) external override { (, , , , MarginFlowProtocolSafety safety, , , , ) = MarginFlowProtocol(protocol).market(); address safetyProtocol = address(safety); require(msg.sender == safetyProtocol, "Ownable: caller is not the protocol safety"); moneyMarket.iToken().safeIncreaseAllowance(safetyProtocol, _iTokenAmount); } /** * @dev Withdraw liquidity for owner. * @param _iTokenAmount The MarginLiquidityPool. * @return The amount withdrawn in base tokens. */ function withdrawLiquidityOwner(uint256 _iTokenAmount) external override onlyOwner returns (uint256) { (, , , , MarginFlowProtocolSafety safety, , , , ) = MarginFlowProtocol(protocol).market(); int256 protocolBalance = MarginFlowProtocol(protocol).balances(this, address(this)); if (protocolBalance > 0) { MarginFlowProtocol(protocol).withdrawForPool(uint256(protocolBalance)); } uint256 baseTokenAmount = moneyMarket.redeemTo(msg.sender, _iTokenAmount); require(safety.isPoolSafe(MarginLiquidityPoolInterface(this)), "Pool not safe after withdrawal"); return baseTokenAmount; } /** * @dev Get amounts of iTokens in pool. * @return The iTokens amount. */ function getLiquidity() external override view returns (uint256) { return moneyMarket.iToken().balanceOf(address(this)); } /** * @dev Get the current bid spread for trading pair. * @return The bid spread. */ function getBidSpread(address _baseToken, address _quoteToken) external override view returns (uint256) { return _getSpread(_baseToken, _quoteToken); } /** * @dev Get the current ask spread for trading pair. * @return The ask spread. */ function getAskSpread(address _baseToken, address _quoteToken) external override view returns (uint256) { return _getSpread(_baseToken, _quoteToken); } /** * @dev Enable the trading pair. * @param _baseToken The base token. * @param _quoteToken The quote token. * @param _spread The initial spread. * @param _newSwapRateMarkup The initial swap rate markup. */ function enableToken( address _baseToken, address _quoteToken, uint256 _spread, int256 _newSwapRateMarkup ) external override onlyOwner { require(_spread != 0, "0"); allowedTokens[_baseToken][_quoteToken] = true; spreadsPerTokenPair[_baseToken][_quoteToken] = _spread; swapRatesMarkups[_baseToken][_quoteToken] = _newSwapRateMarkup; } /** * @dev Disable the trading pair. * @param _baseToken The base token. * @param _quoteToken The quote token. */ function disableToken(address _baseToken, address _quoteToken) external override onlyOwner { allowedTokens[_baseToken][_quoteToken] = false; spreadsPerTokenPair[_baseToken][_quoteToken] = 0; } /** * @dev Set new minimum leverage, only for the owner. * @param _newMinLeverage The new minimum leverage. */ function setMinLeverage(uint256 _newMinLeverage) external override onlyOwner { require(_newMinLeverage > 0, "0"); minLeverage = _newMinLeverage; } /** * @dev Set new maximum leverage, only for the owner. * @param _newMaxLeverage The new maximum leverage. */ function setMaxLeverage(uint256 _newMaxLeverage) external override onlyOwner { require(_newMaxLeverage > 0, "0"); maxLeverage = _newMaxLeverage; } /** * @dev Set new minimum leverage amount, only for the owner. * @param _newMinLeverageAmount The new minimum leverage amount. */ function setMinLeverageAmount(uint256 _newMinLeverageAmount) external override onlyOwner { require(_newMinLeverageAmount > 0, "0"); minLeverageAmount = _newMinLeverageAmount; } /** * @dev Set new swap rate for token pair, only for the owner. * @param _base The base token. * @param _quote The quote token. * @param _newSwapRateMarkup The new swap rate as percentage for longs. */ function setCurrentSwapRateMarkupForPair( address _base, address _quote, int256 _newSwapRateMarkup ) external override onlyOwner { swapRatesMarkups[_base][_quote] = _newSwapRateMarkup; } /** * @dev Get the swap rate markup for trading pair. * @param _baseToken The base token. * @param _quoteToken The quote token. * @return The swap rate markup. */ function getSwapRateMarkupForPair(address _baseToken, address _quoteToken) external override view returns (int256) { return swapRatesMarkups[_baseToken][_quoteToken]; } function _getSpread(address _baseToken, address _quoteToken) private view returns (uint256) { if (allowedTokens[_baseToken][_quoteToken] && spreadsPerTokenPair[_baseToken][_quoteToken] > 0) { return spreadsPerTokenPair[_baseToken][_quoteToken]; } return 0; } }
* @dev Set new swap rate for token pair, only for the owner. @param _base The base token. @param _quote The quote token. @param _newSwapRateMarkup The new swap rate as percentage for longs./
function setCurrentSwapRateMarkupForPair( address _base, address _quote, int256 _newSwapRateMarkup ) external override onlyOwner { swapRatesMarkups[_base][_quote] = _newSwapRateMarkup; }
5,499,743
[ 1, 694, 394, 7720, 4993, 364, 1147, 3082, 16, 1338, 364, 326, 3410, 18, 225, 389, 1969, 1021, 1026, 1147, 18, 225, 389, 6889, 1021, 3862, 1147, 18, 225, 389, 2704, 12521, 4727, 13111, 1021, 394, 7720, 4993, 487, 11622, 364, 4281, 564, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12589, 12521, 4727, 13111, 1290, 4154, 12, 203, 3639, 1758, 389, 1969, 16, 203, 3639, 1758, 389, 6889, 16, 203, 3639, 509, 5034, 389, 2704, 12521, 4727, 13111, 203, 565, 262, 3903, 3849, 1338, 5541, 288, 203, 3639, 7720, 20836, 13111, 87, 63, 67, 1969, 6362, 67, 6889, 65, 273, 389, 2704, 12521, 4727, 13111, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import "./messenger/IMessenger.sol"; /** * @title MessengerRegistry * @dev MessengerRegistry is a contract to register openly distributed Messengers */ contract MessengerRegistry { struct Messenger { address ownerAddress; address messengerAddress; string specificationUrl; uint256 precision; uint256 requestsCounter; uint256 fulfillsCounter; uint256 id; } /// @dev array to store the messengers Messenger[] public messengers; /// @dev (messengerAddress=>bool) to check if the Messenger was mapping(address => bool) public registeredMessengers; /// @dev (userAddress=>messengerAddress[]) to register the messengers of an owner mapping(address => uint256[]) public ownerMessengers; /// @dev (userAddress=>messengerAddress[]) to register the owner of a Messenger address public slaRegistry; event MessengerRegistered( address indexed ownerAddress, address indexed messengerAddress, string specificationUrl, uint256 precision, uint256 id ); event MessengerModified( address indexed ownerAddress, address indexed messengerAddress, string specificationUrl, uint256 precision, uint256 id ); /** * @dev sets the SLARegistry contract address and can only be called * once */ function setSLARegistry() external { // Only able to trigger this function once require( address(slaRegistry) == address(0), "SLARegistry address has already been set" ); slaRegistry = msg.sender; } /** * @dev function to register a new Messenger */ function registerMessenger( address _callerAddress, address _messengerAddress, string calldata _specificationUrl ) external { require( msg.sender == slaRegistry, "Should only be called using the SLARegistry contract" ); require( !registeredMessengers[_messengerAddress], "messenger already registered" ); IMessenger messenger = IMessenger(_messengerAddress); address messengerOwner = messenger.owner(); require( messengerOwner == _callerAddress, "Should only be called by the messenger owner" ); uint256 precision = messenger.messengerPrecision(); uint256 requestsCounter = messenger.requestsCounter(); uint256 fulfillsCounter = messenger.fulfillsCounter(); registeredMessengers[_messengerAddress] = true; uint256 id = messengers.length - 1; ownerMessengers[messengerOwner].push(id); messengers.push( Messenger({ ownerAddress: messengerOwner, messengerAddress: _messengerAddress, specificationUrl: _specificationUrl, precision: precision, requestsCounter: requestsCounter, fulfillsCounter: fulfillsCounter, id: id }) ); emit MessengerRegistered( messengerOwner, _messengerAddress, _specificationUrl, precision, id ); } /** * @dev function to modifyMessenger a Messenger */ function modifyMessenger( string calldata _specificationUrl, uint256 _messengerId ) external { Messenger storage storedMessenger = messengers[_messengerId]; IMessenger messenger = IMessenger(storedMessenger.messengerAddress); require( msg.sender == messenger.owner(), "Can only be modified by the owner" ); storedMessenger.specificationUrl = _specificationUrl; storedMessenger.ownerAddress = msg.sender; emit MessengerModified( storedMessenger.ownerAddress, storedMessenger.messengerAddress, storedMessenger.specificationUrl, storedMessenger.precision, storedMessenger.id ); } function getMessengers() external view returns (Messenger[] memory) { Messenger[] memory returnMessengers = new Messenger[](messengers.length); for (uint256 index = 0; index < messengers.length; index++) { IMessenger messenger = IMessenger(messengers[index].messengerAddress); uint256 requestsCounter = messenger.requestsCounter(); uint256 fulfillsCounter = messenger.fulfillsCounter(); returnMessengers[index] = Messenger({ ownerAddress: messengers[index].ownerAddress, messengerAddress: messengers[index].messengerAddress, specificationUrl: messengers[index].specificationUrl, precision: messengers[index].precision, requestsCounter: requestsCounter, fulfillsCounter: fulfillsCounter, id: messengers[index].id }); } return returnMessengers; } function getMessengersLength() external view returns (uint256) { return messengers.length; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title SLARegistry * @dev SLARegistry is a contract for handling creation of service level * agreements and keeping track of the created agreements */ contract PeriodRegistry is Ownable { using SafeMath for uint256; enum PeriodType {Hourly, Daily, Weekly, BiWeekly, Monthly, Yearly} /// @dev struct to store the definition of a period struct PeriodDefinition { bool initialized; uint256[] starts; uint256[] ends; } /// @dev (periodType=>PeriodDefinition) hourly/weekly/biWeekly/monthly/yearly are periodTypes mapping(PeriodType => PeriodDefinition) public periodDefinitions; /** * @dev event to log a new period initialized *@param periodType 1. period type i.e. Hourly, Daily, Weekly, BiWeekly, Monthly, Yearly *@param periodsAdded 2. amount of periods added */ event PeriodInitialized(PeriodType periodType, uint256 periodsAdded); /** * @dev event to log a new period initialized *@param periodType 1. period type i.e. Hourly, Daily, Weekly, BiWeekly, Monthly, Yearly *@param periodsAdded 2. amount of periods added */ event PeriodModified(PeriodType periodType, uint256 periodsAdded); /** * @dev public function for creating canonical service level agreements *@param _periodType 1. period type i.e. Hourly, Daily, Weekly, BiWeekly, Monthly, Yearly *@param _periodStarts 2. array of the starts of the period *@param _periodEnds 3. array of the ends of the period */ function initializePeriod( PeriodType _periodType, uint256[] memory _periodStarts, uint256[] memory _periodEnds ) public onlyOwner { PeriodDefinition storage periodDefinition = periodDefinitions[_periodType]; require( !periodDefinition.initialized, "Period type already initialized" ); require( _periodStarts.length == _periodEnds.length, "Period type starts and ends should match" ); require(_periodStarts.length > 0, "Period length can't be 0"); for (uint256 index = 0; index < _periodStarts.length; index++) { require( _periodStarts[index] < _periodEnds[index], "Start should be before end" ); if (index < _periodStarts.length - 1) { require( _periodStarts[index + 1].sub(_periodEnds[index]) == 1, "Start of a period should be 1 second after the end of the previous period" ); } periodDefinition.starts.push(_periodStarts[index]); periodDefinition.ends.push(_periodEnds[index]); } periodDefinition.initialized = true; emit PeriodInitialized(_periodType, _periodStarts.length); } /** * @dev function to add new periods to certain period type *@param _periodType 1. period type i.e. Hourly, Daily, Weekly, BiWeekly, Monthly, Yearly *@param _periodStarts 2. array of uint256 of the period starts to add *@param _periodEnds 3. array of uint256 of the period starts to add */ function addPeriodsToPeriodType( PeriodType _periodType, uint256[] memory _periodStarts, uint256[] memory _periodEnds ) public onlyOwner { require(_periodStarts.length > 0, "Period length can't be 0"); PeriodDefinition storage periodDefinition = periodDefinitions[_periodType]; require(periodDefinition.initialized, "Period was not initialized yet"); for (uint256 index = 0; index < _periodStarts.length; index++) { require( _periodStarts[index] < _periodEnds[index], "Start should be before end" ); if (index < _periodStarts.length.sub(1)) { require( _periodStarts[index + 1].sub(_periodEnds[index]) == 1, "Start of a period should be 1 second after the end of the previous period" ); } periodDefinition.starts.push(_periodStarts[index]); periodDefinition.ends.push(_periodEnds[index]); } emit PeriodModified(_periodType, _periodStarts.length); } /** * @dev public function to get the start and end of a period *@param _periodType 1. period type i.e. Hourly, Daily, Weekly, BiWeekly, Monthly, Yearly *@param _periodId 2. period id to get start and end */ function getPeriodStartAndEnd(PeriodType _periodType, uint256 _periodId) public view returns (uint256 start, uint256 end) { start = periodDefinitions[_periodType].starts[_periodId]; end = periodDefinitions[_periodType].ends[_periodId]; } /** * @dev public function to check if a periodType id is initialized *@param _periodType 1. period type i.e. Hourly, Daily, Weekly, BiWeekly, Monthly, Yearly */ function isInitializedPeriod(PeriodType _periodType) public view returns (bool initialized) { PeriodDefinition memory periodDefinition = periodDefinitions[_periodType]; initialized = periodDefinition.initialized; } /** * @dev public function to check if a period id is valid i.e. it belongs to the added id array *@param _periodType 1. period type i.e. Hourly, Daily, Weekly, BiWeekly, Monthly, Yearly *@param _periodId 2. period id to get start and end */ function isValidPeriod(PeriodType _periodType, uint256 _periodId) public view returns (bool valid) { PeriodDefinition memory periodDefinition = periodDefinitions[_periodType]; valid = periodDefinition.starts.length.sub(1) >= _periodId; } /** * @dev public function to check if a period has finished *@param _periodType 1. period type i.e. Hourly, Daily, Weekly, BiWeekly, Monthly, Yearly *@param _periodId 2. period id to get start and end */ function periodIsFinished(PeriodType _periodType, uint256 _periodId) public view returns (bool finished) { require( isValidPeriod(_periodType, _periodId), "Period data is not valid" ); finished = periodDefinitions[_periodType].ends[_periodId] < block.timestamp; } /** * @dev public function to check if a period has started *@param _periodType 1. period type i.e. Hourly, Daily, Weekly, BiWeekly, Monthly, Yearly *@param _periodId 2. period id to get start and end */ function periodHasStarted(PeriodType _periodType, uint256 _periodId) public view returns (bool started) { require( isValidPeriod(_periodType, _periodId), "Period data is not valid" ); started = periodDefinitions[_periodType].starts[_periodId] < block.timestamp; } /** * @dev public function to get the periodDefinitions */ function getPeriodDefinitions() public view returns (PeriodDefinition[] memory) { // 6 period types PeriodDefinition[] memory periodDefinition = new PeriodDefinition[](6); periodDefinition[0] = periodDefinitions[PeriodType.Hourly]; periodDefinition[1] = periodDefinitions[PeriodType.Daily]; periodDefinition[2] = periodDefinitions[PeriodType.Weekly]; periodDefinition[3] = periodDefinitions[PeriodType.BiWeekly]; periodDefinition[4] = periodDefinitions[PeriodType.Monthly]; periodDefinition[5] = periodDefinitions[PeriodType.Yearly]; return periodDefinition; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./SLARegistry.sol"; import "./SLORegistry.sol"; import "./StakeRegistry.sol"; import "./PeriodRegistry.sol"; import "./Staking.sol"; /** * @title SLA * @dev SLA is a service level agreement contract used for service downtime * compensation */ contract SLA is Staking { using SafeMath for uint256; enum Status {NotVerified, Respected, NotRespected} struct PeriodSLI { uint256 timestamp; uint256 sli; Status status; } // string public ipfsHash; address public immutable messengerAddress; SLARegistry public slaRegistry; PeriodRegistry private immutable periodRegistry; SLORegistry private immutable sloRegistry; uint256 public immutable creationBlockNumber; uint128 public immutable initialPeriodId; uint128 public immutable finalPeriodId; PeriodRegistry.PeriodType public immutable periodType; /// @dev extra data for customized workflows bytes32[] public extraData; bool private _breachedContract = false; uint256 public nextVerifiablePeriod; /// @dev periodId=>PeriodSLI mapping mapping(uint256 => PeriodSLI) public periodSLIs; /** * @dev event for SLI creation logging * @param timestamp 1. the time the SLI has been registered * @param sli 2. the value of the SLI * @param periodId 3. the id of the given period */ event SLICreated(uint256 timestamp, uint256 sli, uint256 periodId); /** * @dev event for Stake loging * @param tokenAddress 1. - * @param periodId 2. - * @param amount 3. - * @param caller 4. - */ event Stake( address indexed tokenAddress, uint256 indexed periodId, address indexed caller, uint256 amount ); /** * @dev event for Stake loging * @param tokenAddress 1. - * @param periodId 2. - * @param amount 3. - * @param caller 4. - */ event ProviderWithdraw( address indexed tokenAddress, uint256 indexed periodId, address indexed caller, uint256 amount ); /** * @dev event for Stake loging * @param tokenAddress 1. - * @param periodId 2. - * @param amount 3. - * @param caller 4. - */ event UserWithdraw( address indexed tokenAddress, uint256 indexed periodId, address indexed caller, uint256 amount ); /** * @dev throws if called by any address other than the messenger contract. */ modifier onlyMessenger() { require( msg.sender == messengerAddress, "Only Messenger can call this function" ); _; } /** * @dev throws if called by any address other than the messenger contract. */ modifier onlySLARegistry() { require( msg.sender == address(slaRegistry), "Only SLARegistry can call this function" ); _; } /** * @dev throws if called with an amount less or equal to zero. */ modifier notZero(uint256 _amount) { require(_amount > 0, "amount cannot be 0"); _; } /** * @param _owner 1. - * @param _ipfsHash 3. - * @param _messengerAddress 3. - * @param _initialPeriodId 4. - * @param _finalPeriodId 4. - * @param _periodType 5. - * @param _whitelisted 8. - * @param _extraData 9. - * @param _slaID 10. - */ constructor( address _owner, bool _whitelisted, PeriodRegistry.PeriodType _periodType, address _messengerAddress, uint128 _initialPeriodId, uint128 _finalPeriodId, uint128 _slaID, string memory _ipfsHash, bytes32[] memory _extraData, uint64 _leverage ) public Staking( SLARegistry(msg.sender), _periodType, _whitelisted, _slaID, _leverage, _owner ) { transferOwnership(_owner); ipfsHash = _ipfsHash; messengerAddress = _messengerAddress; slaRegistry = SLARegistry(msg.sender); periodRegistry = slaRegistry.periodRegistry(); sloRegistry = slaRegistry.sloRegistry(); creationBlockNumber = block.number; initialPeriodId = _initialPeriodId; finalPeriodId = _finalPeriodId; periodType = _periodType; extraData = _extraData; nextVerifiablePeriod = _initialPeriodId; } /** * @dev external function to register SLI's and check them against the SLORegistry * @param _sli 1. the value of the SLI to check * @param _periodId 2. the id of the given period */ function registerSLI(uint256 _sli, uint256 _periodId) external onlyMessenger { emit SLICreated(block.timestamp, _sli, _periodId); nextVerifiablePeriod = _periodId + 1; PeriodSLI storage periodSLI = periodSLIs[_periodId]; periodSLI.sli = _sli; periodSLI.timestamp = block.timestamp; (uint256 sloValue, ) = sloRegistry.registeredSLO(address(this)); if (sloRegistry.isRespected(_sli, address(this))) { periodSLI.status = Status.Respected; uint256 precision = 10000; uint256 deviation = _sli.sub(sloValue).mul(precision).div( _sli.add(sloValue).div(2) ); uint256 normalizedPeriodId = _periodId.sub(initialPeriodId).add(1); uint256 rewardPercentage = deviation.mul(normalizedPeriodId).div( finalPeriodId - initialPeriodId + 1 ); _setRespectedPeriodReward(_periodId, rewardPercentage, precision); } else { periodSLI.status = Status.NotRespected; _setUsersCompensation(_periodId); _breachedContract = true; } } function isAllowedPeriod(uint256 _periodId) external view returns (bool) { if (_periodId < initialPeriodId) return false; if (_periodId > finalPeriodId) return false; return true; } function contractFinished() public view returns (bool) { (, uint256 endOfLastValidPeriod) = periodRegistry.getPeriodStartAndEnd(periodType, finalPeriodId); return _breachedContract == true || (block.timestamp >= endOfLastValidPeriod && periodSLIs[finalPeriodId].status != Status.NotVerified); } /** *@dev stake _amount tokens into the _token contract *@param _amount 1. amount to be staked *@param _token 2. address of the ERC to be staked */ function stakeTokens(uint256 _amount, address _token) external notZero(_amount) { bool isContractFinished = contractFinished(); require( !isContractFinished, "Can only stake on not finished contracts" ); _stake(_amount, _token); emit Stake(_token, nextVerifiablePeriod, msg.sender, _amount); StakeRegistry stakeRegistry = slaRegistry.stakeRegistry(); stakeRegistry.registerStakedSla(msg.sender); } function withdrawProviderTokens(uint256 _amount, address _tokenAddress) external notZero(_amount) { bool isContractFinished = contractFinished(); emit ProviderWithdraw( _tokenAddress, nextVerifiablePeriod, msg.sender, _amount ); _withdrawProviderTokens(_amount, _tokenAddress, isContractFinished); } /** *@dev withdraw _amount tokens from the _token contract *@param _amount 1. amount to be staked *@param _tokenAddress 2. address of the ERC to be staked */ function withdrawUserTokens(uint256 _amount, address _tokenAddress) external notZero(_amount) { if (msg.sender != owner()) { bool isContractFinished = contractFinished(); require(isContractFinished, "Only for finished contract"); } emit UserWithdraw( _tokenAddress, nextVerifiablePeriod, msg.sender, _amount ); _withdrawUserTokens(_amount, _tokenAddress); } function getStakersLength() external view returns (uint256) { return stakers.length; } function breachedContract() external view returns (bool) { return _breachedContract; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./SLA.sol"; import "./SLORegistry.sol"; import "./PeriodRegistry.sol"; import "./MessengerRegistry.sol"; import "./StakeRegistry.sol"; import "./messenger/IMessenger.sol"; /** * @title SLARegistry * @dev SLARegistry is a contract for handling creation of service level * agreements and keeping track of the created agreements */ contract SLARegistry { using SafeMath for uint256; /// @dev SLO registry SLORegistry public sloRegistry; /// @dev Periods registry PeriodRegistry public periodRegistry; /// @dev Messengers registry MessengerRegistry public messengerRegistry; /// @dev Stake registry StakeRegistry public stakeRegistry; /// @dev stores the addresses of created SLAs SLA[] public SLAs; /// @dev stores the indexes of service level agreements owned by an user mapping(address => uint256[]) private userToSLAIndexes; /// @dev to check if registered SLA mapping(address => bool) private registeredSLAs; // value to lock past periods on SLA deployment bool public immutable checkPastPeriod; /** * @dev event for service level agreement creation logging * @param sla 1. The address of the created service level agreement contract * @param owner 2. The address of the owner of the service level agreement */ event SLACreated(SLA indexed sla, address indexed owner); /** * @dev event for service level agreement creation logging * @param periodId 1. - * @param sla 2. - * @param caller 3. - */ event SLIRequested( uint256 periodId, address indexed sla, address indexed caller ); /** * @dev event for service level agreement creation logging * @param sla 1. - * @param caller 2. - */ event ReturnLockedValue(address indexed sla, address indexed caller); /** * @dev constructor * @param _sloRegistry 1. SLO Registry * @param _periodRegistry 2. Periods registry * @param _messengerRegistry 3. Messenger registry * @param _stakeRegistry 4. Stake registry * @param _checkPastPeriod 5. - */ constructor( SLORegistry _sloRegistry, PeriodRegistry _periodRegistry, MessengerRegistry _messengerRegistry, StakeRegistry _stakeRegistry, bool _checkPastPeriod ) public { sloRegistry = _sloRegistry; sloRegistry.setSLARegistry(); periodRegistry = _periodRegistry; stakeRegistry = _stakeRegistry; stakeRegistry.setSLARegistry(); messengerRegistry = _messengerRegistry; messengerRegistry.setSLARegistry(); checkPastPeriod = _checkPastPeriod; } /** * @dev public function for creating canonical service level agreements * @param _sloValue 1. - * @param _sloType 2. - * @param _ipfsHash 3. - * @param _periodType 4. - * @param _initialPeriodId 5. - * @param _finalPeriodId 6. - * @param _messengerAddress 7. - * @param _whitelisted 8. - * @param _extraData 9. - * @param _leverage 10. - */ function createSLA( uint256 _sloValue, SLORegistry.SLOType _sloType, bool _whitelisted, address _messengerAddress, PeriodRegistry.PeriodType _periodType, uint128 _initialPeriodId, uint128 _finalPeriodId, string memory _ipfsHash, bytes32[] memory _extraData, uint64 _leverage ) public { bool validPeriod = periodRegistry.isValidPeriod(_periodType, _initialPeriodId); require(validPeriod, "First period id not valid"); validPeriod = periodRegistry.isValidPeriod(_periodType, _finalPeriodId); require(validPeriod, "Final period id not valid"); bool initializedPeriod = periodRegistry.isInitializedPeriod(_periodType); require(initializedPeriod, "Period type not initialized yet"); require( _finalPeriodId >= _initialPeriodId, "invalid finalPeriodId and initialPeriodId" ); if (checkPastPeriod) { bool periodHasStarted = periodRegistry.periodHasStarted(_periodType, _initialPeriodId); require(!periodHasStarted, "Period has started"); } bool registeredMessenger = messengerRegistry.registeredMessengers(_messengerAddress); require(registeredMessenger == true, "messenger not registered"); SLA sla = new SLA( msg.sender, _whitelisted, _periodType, _messengerAddress, _initialPeriodId, _finalPeriodId, uint128(SLAs.length), _ipfsHash, _extraData, _leverage ); sloRegistry.registerSLO(_sloValue, _sloType, address(sla)); stakeRegistry.lockDSLAValue( msg.sender, address(sla), _finalPeriodId - _initialPeriodId + 1 ); SLAs.push(sla); registeredSLAs[address(sla)] = true; uint256 index = SLAs.length.sub(1); userToSLAIndexes[msg.sender].push(index); emit SLACreated(sla, msg.sender); } /** * @dev Gets SLI information for the specified SLA and SLO * @param _periodId 1. id of the period * @param _sla 2. SLA Address * @param _ownerApproval 3. if approval by owner or msg.sender */ function requestSLI( uint256 _periodId, SLA _sla, bool _ownerApproval ) public { require(isRegisteredSLA(address(_sla)), "invalid SLA"); require(_periodId == _sla.nextVerifiablePeriod(), "invalid periodId"); (, , SLA.Status status) = _sla.periodSLIs(_periodId); require(status == SLA.Status.NotVerified, "invalid SLA status"); bool breachedContract = _sla.breachedContract(); require(!breachedContract, "breached contract"); bool slaAllowedPeriodId = _sla.isAllowedPeriod(_periodId); require(slaAllowedPeriodId, "invalid period Id"); PeriodRegistry.PeriodType slaPeriodType = _sla.periodType(); bool periodFinished = periodRegistry.periodIsFinished(slaPeriodType, _periodId); require(periodFinished, "period not finished"); address slaMessenger = _sla.messengerAddress(); SLIRequested(_periodId, address(_sla), msg.sender); IMessenger(slaMessenger).requestSLI( _periodId, address(_sla), _ownerApproval, msg.sender ); stakeRegistry.distributeVerificationRewards( address(_sla), msg.sender, _periodId ); } function returnLockedValue(SLA _sla) public { require(isRegisteredSLA(address(_sla)), "invalid SLA"); require(msg.sender == _sla.owner(), "msg.sender not owner"); uint256 lastValidPeriodId = _sla.finalPeriodId(); PeriodRegistry.PeriodType periodType = _sla.periodType(); (, uint256 endOfLastValidPeriod) = periodRegistry.getPeriodStartAndEnd(periodType, lastValidPeriodId); (, , SLA.Status lastPeriodStatus) = _sla.periodSLIs(lastValidPeriodId); require( _sla.breachedContract() || (block.timestamp >= endOfLastValidPeriod && lastPeriodStatus != SLA.Status.NotVerified), "Should only withdraw for finished contracts" ); ReturnLockedValue(address(_sla), msg.sender); stakeRegistry.returnLockedValue(address(_sla)); } /** * @dev function to declare this SLARegistry contract as SLARegistry of _messengerAddress * @param _messengerAddress 1. address of the messenger */ function registerMessenger( address _messengerAddress, string memory _specificationUrl ) public { IMessenger(_messengerAddress).setSLARegistry(); messengerRegistry.registerMessenger( msg.sender, _messengerAddress, _specificationUrl ); } /** * @dev public view function that returns the service level agreements that * the given user is the owner of * @param _user Address of the user for which to return the service level * agreements * @return array of SLAs */ function userSLAs(address _user) public view returns (SLA[] memory) { uint256 count = userToSLAIndexes[_user].length; SLA[] memory SLAList = new SLA[](count); uint256[] memory userSLAIndexes = userToSLAIndexes[_user]; for (uint256 i = 0; i < count; i++) { SLAList[i] = (SLAs[userSLAIndexes[i]]); } return (SLAList); } /** * @dev public view function that returns all the service level agreements * @return SLA[] array of SLAs */ function allSLAs() public view returns (SLA[] memory) { return (SLAs); } /** * @dev public view function that returns true if _slaAddress was deployed using this SLARegistry * @param _slaAddress address of the SLA to be checked */ function isRegisteredSLA(address _slaAddress) public view returns (bool) { return registeredSLAs[_slaAddress]; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; pragma experimental ABIEncoderV2; /** * @title SLORegistry * @dev SLORegistry is a contract for handling creation of service level * objectives and querying those service level objectives */ contract SLORegistry { enum SLOType { EqualTo, NotEqualTo, SmallerThan, SmallerOrEqualTo, GreaterThan, GreaterOrEqualTo } struct SLO { uint256 sloValue; SLOType sloType; } /** * @dev SLO Registered event * @param sla 1. - * @param sloValue 2. - * @param sloType 3. - */ event SLORegistered(address indexed sla, uint256 sloValue, SLOType sloType); address private slaRegistry; mapping(address => SLO) public registeredSLO; modifier onlySLARegistry { require( msg.sender == slaRegistry, "Should only be called using the SLARegistry contract" ); _; } function setSLARegistry() public { // Only able to trigger this function once require( address(slaRegistry) == address(0), "SLARegistry address has already been set" ); slaRegistry = msg.sender; } /** * @dev public function for creating service level objectives * @param _sloValue 1. - * @param _sloType 2. - * @param _slaAddress 3. - */ function registerSLO( uint256 _sloValue, SLOType _sloType, address _slaAddress ) public onlySLARegistry { registeredSLO[_slaAddress] = SLO({ sloValue: _sloValue, sloType: _sloType }); emit SLORegistered(_slaAddress, _sloValue, _sloType); } /** * @dev external view function to check a value against the SLO * @param _value The SLI value to check against the SL * @return boolean with the SLO honored state */ function isRespected(uint256 _value, address _slaAddress) public view returns (bool) { SLO memory slo = registeredSLO[_slaAddress]; SLOType sloType = slo.sloType; uint256 sloValue = slo.sloValue; if (sloType == SLOType.EqualTo) { return _value == sloValue; } if (sloType == SLOType.NotEqualTo) { return _value != sloValue; } if (sloType == SLOType.SmallerThan) { return _value < sloValue; } if (sloType == SLOType.SmallerOrEqualTo) { return _value <= sloValue; } if (sloType == SLOType.GreaterThan) { return _value > sloValue; } if (sloType == SLOType.GreaterOrEqualTo) { return _value >= sloValue; } revert("isRespected wasn't executed properly"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./SLA.sol"; import "./messenger/IMessenger.sol"; import "./SLARegistry.sol"; import "./StringUtils.sol"; /** * @title StakeRegistry * @dev StakeRegistry is a contract to register the staking activity of the platform, along with controlling certain admin privileged parameters */ contract StakeRegistry is Ownable, ReentrancyGuard { using SafeERC20 for ERC20; using SafeMath for uint256; /// @dev struct to return on getActivePool function. struct ActivePool { address SLAAddress; uint256 stake; string assetName; address assetAddress; } struct LockedValue { uint256 lockedValue; uint256 slaPeriodIdsLength; uint256 dslaDepositByPeriod; uint256 dslaPlatformReward; uint256 dslaMessengerReward; uint256 dslaUserReward; uint256 dslaBurnedByVerification; mapping(uint256 => bool) verifiedPeriods; } address public DSLATokenAddress; SLARegistry public slaRegistry; //______ onlyOwner modifiable parameters ______ /// @dev corresponds to the burn rate of DSLA tokens, but divided by 1000 i.e burn percentage = DSLAburnRate/1000 % uint256 private _DSLAburnRate = 3; /// @dev (ownerAddress => slaAddress => LockedValue) stores the locked value by the staker mapping(address => LockedValue) public slaLockedValue; /// @dev DSLA deposit by period to create SLA uint256 private _dslaDepositByPeriod = 1000 ether; /// @dev DSLA rewarded to the foundation uint256 private _dslaPlatformReward = 250 ether; /// @dev DSLA rewarded to the Messenger creator uint256 private _dslaMessengerReward = 250 ether; /// @dev DSLA rewarded to user calling the period verification uint256 private _dslaUserReward = 250 ether; /// @dev DSLA burned after every period verification uint256 private _dslaBurnedByVerification = 250 ether; /// @dev max token length for allowedTokens array of Staking contracts uint256 private _maxTokenLength = 1; /// @dev max times of hedge leverage uint64 private _maxLeverage = 100; /// @dev array with the allowed tokens addresses of the StakeRegistry address[] public allowedTokens; /// @dev (userAddress => SLA[]) with user staked SLAs to get tokenPool mapping(address => SLA[]) public userStakedSlas; /** * @dev event to log a verifiation reward distributed * @param sla 1. The address of the created service level agreement contract * @param requester 2. - * @param userReward 3. - * @param platformReward 4. - * @param messengerReward 5. - * @param burnedDSLA 6. - */ event VerificationRewardDistributed( address indexed sla, address indexed requester, uint256 userReward, uint256 platformReward, uint256 messengerReward, uint256 burnedDSLA ); /** * @dev event to log modifications on the staking parameters *@param DSLAburnRate 1. (DSLAburnRate/1000)% of DSLA to be burned after a reward/compensation is paid *@param dslaDepositByPeriod 2. DSLA deposit by period to create SLA *@param dslaPlatformReward 3. DSLA rewarded to Stacktical team *@param dslaUserReward 4. DSLA rewarded to user calling the period verification *@param dslaBurnedByVerification 5. DSLA burned after every period verification */ event StakingParametersModified( uint256 DSLAburnRate, uint256 dslaDepositByPeriod, uint256 dslaPlatformReward, uint256 dslaMessengerReward, uint256 dslaUserReward, uint256 dslaBurnedByVerification, uint256 maxTokenLength, uint64 maxLeverage ); /** * @dev event to log modifications on the staking parameters *@param sla 1. - *@param owner 2. - *@param amount 3. - */ event LockedValueReturned( address indexed sla, address indexed owner, uint256 amount ); /** * @dev event to log modifications on the staking parameters *@param dTokenAddress 1. - *@param sla 2. - *@param name 3. - *@param symbol 4. - */ event DTokenCreated( address indexed dTokenAddress, address indexed sla, string name, string symbol ); /** * @dev event to log modifications on the staking parameters *@param sla 1. - *@param owner 2. - *@param amount 3. - */ event ValueLocked( address indexed sla, address indexed owner, uint256 amount ); /** * @param _dslaTokenAddress 1. DSLA Token */ constructor(address _dslaTokenAddress) public { require( _dslaDepositByPeriod == _dslaPlatformReward .add(_dslaMessengerReward) .add(_dslaUserReward) .add(_dslaBurnedByVerification), "Staking parameters should match on summation" ); DSLATokenAddress = _dslaTokenAddress; allowedTokens.push(_dslaTokenAddress); } /// @dev Throws if called by any address other than the SLARegistry contract or Chainlink Oracle. modifier onlySLARegistry() { require( msg.sender == address(slaRegistry), "Can only be called by SLARegistry" ); _; } /** * @dev sets the SLARegistry contract address and can only be called * once */ function setSLARegistry() external { // Only able to trigger this function once require( address(slaRegistry) == address(0), "SLARegistry address has already been set" ); slaRegistry = SLARegistry(msg.sender); } /** *@dev add a token to ve allowed for staking *@param _tokenAddress 1. address of the new allowed token */ function addAllowedTokens(address _tokenAddress) external onlyOwner { require(!isAllowedToken(_tokenAddress), "token already added"); allowedTokens.push(_tokenAddress); } function isAllowedToken(address _tokenAddress) public view returns (bool) { for (uint256 index = 0; index < allowedTokens.length; index++) { if (allowedTokens[index] == _tokenAddress) { return true; } } return false; } /** *@dev public view function that returns true if the _owner has staked on _sla *@param _user 1. address to check *@param _sla 2. sla to check *@return bool, true if _sla was staked by _user */ function slaWasStakedByUser(address _user, address _sla) public view returns (bool) { for (uint256 index = 0; index < userStakedSlas[_user].length; index++) { if (address(userStakedSlas[_user][index]) == _sla) { return true; } } return false; } /** *@dev register the sending SLA contract as staked by _owner *@param _owner 1. SLA contract to stake */ function registerStakedSla(address _owner) external returns (bool) { require( slaRegistry.isRegisteredSLA(msg.sender), "Only for registered SLAs" ); if (!slaWasStakedByUser(_owner, msg.sender)) { userStakedSlas[_owner].push(SLA(msg.sender)); } return true; } /** *@dev to create dTokens for staking *@param _name 1. token name *@param _symbol 2. token symbol */ function createDToken(string calldata _name, string calldata _symbol) external returns (address) { require( slaRegistry.isRegisteredSLA(msg.sender), "Only for registered SLAs" ); ERC20PresetMinterPauser dToken = new ERC20PresetMinterPauser(_name, _symbol); dToken.grantRole(dToken.MINTER_ROLE(), msg.sender); emit DTokenCreated(address(dToken), msg.sender, _name, _symbol); return address(dToken); } function lockDSLAValue( address _slaOwner, address _sla, uint256 _periodIdsLength ) external onlySLARegistry nonReentrant { uint256 lockedValue = _dslaDepositByPeriod.mul(_periodIdsLength); ERC20(DSLATokenAddress).safeTransferFrom( _slaOwner, address(this), lockedValue ); slaLockedValue[_sla] = LockedValue({ lockedValue: lockedValue, slaPeriodIdsLength: _periodIdsLength, dslaDepositByPeriod: _dslaDepositByPeriod, dslaPlatformReward: _dslaPlatformReward, dslaMessengerReward: _dslaMessengerReward, dslaUserReward: _dslaUserReward, dslaBurnedByVerification: _dslaBurnedByVerification }); emit ValueLocked(_sla, _slaOwner, lockedValue); } function distributeVerificationRewards( address _sla, address _verificationRewardReceiver, uint256 _periodId ) external onlySLARegistry nonReentrant { LockedValue storage _lockedValue = slaLockedValue[_sla]; require( !_lockedValue.verifiedPeriods[_periodId], "Period rewards already distributed" ); _lockedValue.verifiedPeriods[_periodId] = true; _lockedValue.lockedValue = _lockedValue.lockedValue.sub( _lockedValue.dslaDepositByPeriod ); ERC20(DSLATokenAddress).safeTransfer( _verificationRewardReceiver, _lockedValue.dslaUserReward ); ERC20(DSLATokenAddress).safeTransfer( owner(), _lockedValue.dslaPlatformReward ); ERC20(DSLATokenAddress).safeTransfer( IMessenger(SLA(_sla).messengerAddress()).owner(), _lockedValue.dslaMessengerReward ); _burnDSLATokens(_lockedValue.dslaBurnedByVerification); emit VerificationRewardDistributed( _sla, _verificationRewardReceiver, _lockedValue.dslaUserReward, _lockedValue.dslaPlatformReward, _lockedValue.dslaMessengerReward, _lockedValue.dslaBurnedByVerification ); } function returnLockedValue(address _sla) external onlySLARegistry nonReentrant { LockedValue storage _lockedValue = slaLockedValue[_sla]; uint256 remainingBalance = _lockedValue.lockedValue; require(remainingBalance > 0, "locked value is empty"); _lockedValue.lockedValue = 0; ERC20(DSLATokenAddress).safeTransfer( SLA(_sla).owner(), remainingBalance ); emit LockedValueReturned(_sla, SLA(_sla).owner(), remainingBalance); } function _burnDSLATokens(uint256 _amount) internal { bytes4 BURN_SELECTOR = bytes4(keccak256(bytes("burn(uint256)"))); (bool _success, ) = DSLATokenAddress.call( abi.encodeWithSelector(BURN_SELECTOR, _amount) ); require(_success, "DSLA burn process was not successful"); } /** * @dev returns the active pools owned by a user. * @param _slaOwner 1. owner of the active pool * @return ActivePool[], array of structs: {SLAAddress,stake,assetName} */ function getActivePool(address _slaOwner) external view returns (ActivePool[] memory) { bytes4 NAME_SELECTOR = bytes4(keccak256(bytes("name()"))); uint256 stakeCounter = 0; // Count the stakes of the user, checking every SLA staked for ( uint256 index = 0; index < userStakedSlas[_slaOwner].length; index++ ) { SLA currentSLA = SLA(userStakedSlas[_slaOwner][index]); stakeCounter = stakeCounter.add( currentSLA.getAllowedTokensLength() ); } ActivePool[] memory activePools = new ActivePool[](stakeCounter); // to insert on activePools array uint256 stakePosition = 0; for ( uint256 index = 0; index < userStakedSlas[_slaOwner].length; index++ ) { SLA currentSLA = userStakedSlas[_slaOwner][index]; for ( uint256 tokenIndex = 0; tokenIndex < currentSLA.getAllowedTokensLength(); tokenIndex++ ) { (address tokenAddress, uint256 stake) = currentSLA.getTokenStake(_slaOwner, tokenIndex); (, bytes memory tokenNameBytes) = tokenAddress.staticcall( abi.encodeWithSelector(NAME_SELECTOR) ); ActivePool memory currentActivePool = ActivePool({ SLAAddress: address(currentSLA), stake: stake, assetName: string(tokenNameBytes), assetAddress: tokenAddress }); activePools[stakePosition] = currentActivePool; stakePosition = stakePosition.add(1); } } return activePools; } //_______ OnlyOwner functions _______ function setStakingParameters( uint256 DSLAburnRate, uint256 dslaDepositByPeriod, uint256 dslaPlatformReward, uint256 dslaMessengerReward, uint256 dslaUserReward, uint256 dslaBurnedByVerification, uint256 maxTokenLength, uint64 maxLeverage ) external onlyOwner { _DSLAburnRate = DSLAburnRate; _dslaDepositByPeriod = dslaDepositByPeriod; _dslaPlatformReward = dslaPlatformReward; _dslaMessengerReward = dslaMessengerReward; _dslaUserReward = dslaUserReward; _dslaBurnedByVerification = dslaBurnedByVerification; _maxTokenLength = maxTokenLength; _maxLeverage = maxLeverage; require( _dslaDepositByPeriod == _dslaPlatformReward .add(_dslaMessengerReward) .add(_dslaUserReward) .add(_dslaBurnedByVerification), "Staking parameters should match on summation" ); emit StakingParametersModified( DSLAburnRate, dslaDepositByPeriod, dslaPlatformReward, dslaMessengerReward, dslaUserReward, dslaBurnedByVerification, maxTokenLength, maxLeverage ); } function getStakingParameters() external view returns ( uint256 DSLAburnRate, uint256 dslaDepositByPeriod, uint256 dslaPlatformReward, uint256 dslaMessengerReward, uint256 dslaUserReward, uint256 dslaBurnedByVerification, uint256 maxTokenLength, uint64 maxLeverage ) { DSLAburnRate = _DSLAburnRate; dslaDepositByPeriod = _dslaDepositByPeriod; dslaPlatformReward = _dslaPlatformReward; dslaMessengerReward = _dslaMessengerReward; dslaUserReward = _dslaUserReward; dslaBurnedByVerification = _dslaBurnedByVerification; maxTokenLength = _maxTokenLength; maxLeverage = _maxLeverage; } function periodIsVerified(address _sla, uint256 _periodId) external view returns (bool) { return slaLockedValue[_sla].verifiedPeriods[_periodId]; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./StakeRegistry.sol"; import "./SLARegistry.sol"; import "./PeriodRegistry.sol"; import "./StringUtils.sol"; contract Staking is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; /// @dev StakeRegistry contract StakeRegistry private stakeRegistry; /// @dev SLARegistry contract PeriodRegistry private immutable periodRegistry; /// @dev current SLA id uint128 public immutable slaID; /// @dev (tokenAddress=>uint256) total pooled token balance mapping(address => uint256) public providerPool; /// @dev (tokenAddress=>uint256) total pooled token balance mapping(address => uint256) public usersPool; ///@dev (tokenAddress=>dTokenAddress) to keep track of dToken for users mapping(address => ERC20PresetMinterPauser) public duTokenRegistry; ///@dev (tokenAddress=>dTokenAddress) to keep track of dToken for provider mapping(address => ERC20PresetMinterPauser) public dpTokenRegistry; /// @dev address[] of the stakers of the SLA contract address[] public stakers; /// @dev (slaOwner=>bool) mapping(address => bool) public registeredStakers; /// @dev DSLA token address to burn fees address public immutable dslaTokenAddress; /// @dev array with the allowed tokens addresses for the current SLA address[] public allowedTokens; /// @dev corresponds to the burn rate of DSLA tokens, but divided by 1000 i.e burn percentage = burnRate/1000 % uint256 public immutable DSLAburnRate; /// @dev PeriodRegistry period type of the SLA contract PeriodRegistry.PeriodType private immutable periodType; /// @dev boolean to declare if contract is whitelisted bool public immutable whitelistedContract; /// @dev (userAddress=bool) to declare whitelisted addresses mapping(address => bool) public whitelist; uint64 public immutable leverage; modifier onlyAllowedToken(address _token) { require(isAllowedToken(_token) == true, "token is not allowed"); _; } modifier onlyWhitelisted { if (whitelistedContract == true) { require(whitelist[msg.sender] == true, "Not whitelisted"); } _; } /** * @dev event for provider reward log * @param periodId 1. id of the period * @param tokenAddress 2. address of the token * @param rewardPercentage 3. reward percentage for the provider * @param rewardPercentagePrecision 4. reward percentage for the provider * @param rewardAmount 5. amount rewarded */ event ProviderRewardGenerated( uint256 indexed periodId, address indexed tokenAddress, uint256 rewardPercentage, uint256 rewardPercentagePrecision, uint256 rewardAmount ); event UserCompensationGenerated( uint256 indexed periodId, address indexed tokenAddress, uint256 usersStake, uint256 leverage, uint256 compensation ); event DTokensCreated( address indexed tokenAddress, address indexed dpTokenAddress, string dpTokenName, string dpTokenSymbol, address indexed duTokenAddress, string duTokenName, string duTokenSymbol ); /** *@param _slaRegistryAddress 1. period type of the SLA *@param _periodType 3. period type of the SLA *@param _whitelistedContract 5. enables the white list feature *@param _slaID 6. identifies the SLA to uniquely to emit dTokens */ constructor( SLARegistry _slaRegistry, PeriodRegistry.PeriodType _periodType, bool _whitelistedContract, uint128 _slaID, uint64 _leverage, address _contractOwner ) public { stakeRegistry = _slaRegistry.stakeRegistry(); periodRegistry = _slaRegistry.periodRegistry(); periodType = _periodType; whitelistedContract = _whitelistedContract; (uint256 _DSLAburnRate, , , , , , , uint64 _maxLeverage) = stakeRegistry.getStakingParameters(); dslaTokenAddress = stakeRegistry.DSLATokenAddress(); DSLAburnRate = _DSLAburnRate; whitelist[_contractOwner] = true; slaID = _slaID; require( _leverage <= _maxLeverage && _leverage >= 1, "Incorrect leverage" ); leverage = _leverage; } function addUsersToWhitelist(address[] memory _userAddresses) public onlyOwner { for (uint256 index = 0; index < _userAddresses.length; index++) { if (whitelist[_userAddresses[index]] == false) { whitelist[_userAddresses[index]] = true; } } } function removeUsersFromWhitelist(address[] calldata _userAddresses) external onlyOwner { for (uint256 index = 0; index < _userAddresses.length; index++) { if (whitelist[_userAddresses[index]] == true) { whitelist[_userAddresses[index]] = false; } } } /** *@dev add a token to ve allowed for staking *@param _tokenAddress 1. address of the new allowed token */ function addAllowedTokens(address _tokenAddress) external onlyOwner { (, , , , , , uint256 maxTokenLength, ) = stakeRegistry.getStakingParameters(); require(!isAllowedToken(_tokenAddress), "Token already added"); require( stakeRegistry.isAllowedToken(_tokenAddress), "Token not allowed by the SLARegistry contract" ); allowedTokens.push(_tokenAddress); require( maxTokenLength >= allowedTokens.length, "Allowed tokens length greater than max token length" ); string memory dTokenID = StringUtils.uintToStr(slaID); string memory duTokenName = string(abi.encodePacked("DSLA-SHORT-", dTokenID)); string memory duTokenSymbol = string(abi.encodePacked("DSLA-SP-", dTokenID)); string memory dpTokenName = string(abi.encodePacked("DSLA-LONG-", dTokenID)); string memory dpTokenSymbol = string(abi.encodePacked("DSLA-LP-", dTokenID)); ERC20PresetMinterPauser duToken = ERC20PresetMinterPauser( stakeRegistry.createDToken(duTokenName, duTokenSymbol) ); ERC20PresetMinterPauser dpToken = ERC20PresetMinterPauser( stakeRegistry.createDToken(dpTokenName, dpTokenSymbol) ); dpTokenRegistry[_tokenAddress] = dpToken; duTokenRegistry[_tokenAddress] = duToken; emit DTokensCreated( _tokenAddress, address(dpToken), dpTokenName, dpTokenName, address(duToken), duTokenName, duTokenName ); } /** *@dev increase the amount staked per token *@param _amount 1. amount to be staked *@param _tokenAddress 2. address of the token *@notice providers can stake at any time *@notice users can stake at any time but no more than provider pool */ function _stake(uint256 _amount, address _tokenAddress) internal onlyAllowedToken(_tokenAddress) onlyWhitelisted { ERC20(_tokenAddress).safeTransferFrom( msg.sender, address(this), _amount ); //duTokens if (msg.sender != owner()) { (uint256 providerStake, uint256 usersStake) = (providerPool[_tokenAddress], usersPool[_tokenAddress]); require( usersStake.add(_amount).mul(leverage) <= providerStake, "Incorrect user stake" ); ERC20PresetMinterPauser duToken = duTokenRegistry[_tokenAddress]; uint256 p0 = duToken.totalSupply(); // if there's no minted tokens, then create 1-1 proportion if (p0 == 0) { duToken.mint(msg.sender, _amount); } else { uint256 t0 = usersPool[_tokenAddress]; // mint dTokens proportionally uint256 mintedDUTokens = _amount.mul(p0).div(t0); duToken.mint(msg.sender, mintedDUTokens); } usersPool[_tokenAddress] = usersPool[_tokenAddress].add(_amount); //dpTokens } else { ERC20PresetMinterPauser dpToken = dpTokenRegistry[_tokenAddress]; uint256 p0 = dpToken.totalSupply(); if (p0 == 0) { dpToken.mint(msg.sender, _amount); } else { uint256 t0 = providerPool[_tokenAddress]; // mint dTokens proportionally uint256 mintedDPTokens = _amount.mul(p0).div(t0); dpToken.mint(msg.sender, mintedDPTokens); } providerPool[_tokenAddress] = providerPool[_tokenAddress].add( _amount ); } if (registeredStakers[msg.sender] == false) { registeredStakers[msg.sender] = true; stakers.push(msg.sender); } } /** *@dev sets the provider reward *@notice it calculates the usersStake and calculates the provider reward from it. * @param _periodId 1. id of the period * @param _rewardPercentage to calculate the provider reward * @param _precision used to avoid getting 0 after division in the SLA's registerSLI function */ function _setRespectedPeriodReward( uint256 _periodId, uint256 _rewardPercentage, uint256 _precision ) internal { for (uint256 index = 0; index < allowedTokens.length; index++) { address tokenAddress = allowedTokens[index]; uint256 usersStake = usersPool[tokenAddress]; uint256 reward = usersStake.mul(_rewardPercentage).div(_precision); usersPool[tokenAddress] = usersPool[tokenAddress].sub(reward); providerPool[tokenAddress] = providerPool[tokenAddress].add(reward); emit ProviderRewardGenerated( _periodId, tokenAddress, _rewardPercentage, _precision, reward ); } } /** *@dev sets the users compensation pool *@notice it calculates the usersStake and calculates the users compensation from it */ function _setUsersCompensation(uint256 _periodId) internal { for (uint256 index = 0; index < allowedTokens.length; index++) { address tokenAddress = allowedTokens[index]; uint256 usersStake = usersPool[tokenAddress]; uint256 compensation = usersStake.mul(leverage); providerPool[tokenAddress] = providerPool[tokenAddress].sub( compensation ); usersPool[tokenAddress] = usersPool[tokenAddress].add(compensation); emit UserCompensationGenerated( _periodId, tokenAddress, usersStake, leverage, compensation ); } } /** *@dev withdraw staked tokens. Only dpToken owners can withdraw, *@param _amount 1. amount to be withdrawn *@param _tokenAddress 2. address of the token *@param _contractFinished 3. contract finished */ function _withdrawProviderTokens( uint256 _amount, address _tokenAddress, bool _contractFinished ) internal onlyAllowedToken(_tokenAddress) { uint256 providerStake = providerPool[_tokenAddress]; uint256 usersStake = usersPool[_tokenAddress]; if (!_contractFinished) { require( providerStake.sub(_amount) >= usersStake.mul(leverage), "Incorrect withdraw" ); } ERC20PresetMinterPauser dpToken = dpTokenRegistry[_tokenAddress]; uint256 p0 = dpToken.totalSupply(); uint256 t0 = providerPool[_tokenAddress]; // Burn duTokens in a way that it doesn't affect the PoolTokens/LPTokens average // t0/p0 = (t0-_amount)/(p0-burnedDPTokens) // burnedDPTokens = _amount*p0/t0 uint256 burnedDPTokens = _amount.mul(p0).div(t0); dpToken.burnFrom(msg.sender, burnedDPTokens); providerPool[_tokenAddress] = providerPool[_tokenAddress].sub(_amount); ERC20(_tokenAddress).safeTransfer(msg.sender, _amount); } /** *@dev withdraw staked tokens. Only duToken owners can withdraw, *@param _amount 1. amount to be withdrawn *@param _tokenAddress 2. address of the token */ function _withdrawUserTokens(uint256 _amount, address _tokenAddress) internal onlyAllowedToken(_tokenAddress) { ERC20PresetMinterPauser duToken = duTokenRegistry[_tokenAddress]; uint256 p0 = duToken.totalSupply(); uint256 t0 = usersPool[_tokenAddress]; // Burn duTokens in a way that it doesn't affect the PoolTokens/LPTokens // average for current period. // t0/p0 = (t0-_amount)/(p0-burnedDUTokens) // burnedDUTokens = _amount*p0/t0 uint256 burnedDUTokens = _amount.mul(p0).div(t0); duToken.burnFrom(msg.sender, burnedDUTokens); usersPool[_tokenAddress] = usersPool[_tokenAddress].sub(_amount); ERC20(_tokenAddress).safeTransfer(msg.sender, _amount); } /** *@dev use this function to evaluate the length of the allowed tokens length *@return allowedTokens.length */ function getAllowedTokensLength() external view returns (uint256) { return allowedTokens.length; } function getTokenStake(address _staker, uint256 _allowedTokenIndex) external view returns (address tokenAddress, uint256 stake) { address allowedTokenAddress = allowedTokens[_allowedTokenIndex]; if (_staker == owner()) { return (allowedTokenAddress, providerPool[allowedTokenAddress]); } else { ERC20PresetMinterPauser dToken = duTokenRegistry[allowedTokenAddress]; uint256 dTokenSupply = dToken.totalSupply(); if (dTokenSupply == 0) { return (allowedTokenAddress, 0); } uint256 dTokenBalance = dToken.balanceOf(_staker); return ( allowedTokenAddress, usersPool[allowedTokenAddress].mul(dTokenBalance).div( dTokenSupply ) ); } } /** *@dev checks in the allowedTokens array if there's a token with _tokenAddress value *@param _tokenAddress 1. token address to check exixtence *@return true if _tokenAddress exists in the allowedTokens array */ function isAllowedToken(address _tokenAddress) public view returns (bool) { for (uint256 index = 0; index < allowedTokens.length; index++) { if (allowedTokens[index] == _tokenAddress) { return true; } } return false; } } // solhint-disable-line pragma solidity 0.6.6; library StringUtils { function addressToString(address _address) external pure returns (string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _string = new bytes(42); _string[0] = "0"; _string[1] = "x"; for (uint256 i = 0; i < 20; i++) { _string[2 + i * 2] = HEX[uint8(_bytes[i + 12] >> 4)]; _string[3 + i * 2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_string); } function bytes32ToStr(bytes32 _bytes32) external pure returns (string memory) { uint8 i = 0; while (i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } function bytesToUint(bytes calldata b) external pure returns (uint256 result) { result = 0; for (uint256 i = 0; i < b.length; i++) { if (uint8(b[i]) >= 48 && uint8(b[i]) <= 57) { result = result * 10 + (uint8(b[i]) - 48); } } return result; } /* ORACLIZE_API Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ function uintToStr(uint256 _i) external pure returns (string memory _uintAsString) { uint256 number = _i; if (number == 0) { return "0"; } uint256 j = number; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (number != 0) { bstr[k--] = bytes1(uint8(48 + (number % 10))); number /= 10; } return string(bstr); } } pragma solidity 0.6.6; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title IMessenger * @dev Interface to create new Messenger contract to add lo Messenger lists */ abstract contract IMessenger is Ownable { struct SLIRequest { address slaAddress; uint256 periodId; } /** * @dev event emitted when having a response from Chainlink with the SLI * @param slaAddress 1. SLA address to store the SLI * @param periodId 2. id of the Chainlink request * @param requestId 3. id of the Chainlink request * @param chainlinkResponse 4. response from Chainlink */ event SLIReceived( address indexed slaAddress, uint256 periodId, bytes32 indexed requestId, bytes32 chainlinkResponse ); /** * @dev sets the SLARegistry contract address and can only be called once */ function setSLARegistry() external virtual; /** * @dev creates a ChainLink request to get a new SLI value for the * given params. Can only be called by the SLARegistry contract or Chainlink Oracle. * @param _periodId 1. id of the period to be queried * @param _slaAddress 2. address of the receiver SLA * @param _slaAddress 2. if approval by owner or msg.sender */ function requestSLI( uint256 _periodId, address _slaAddress, bool _ownerApproval, address _callerAddress ) external virtual; /** * @dev callback function for the Chainlink SLI request which stores * the SLI in the SLA contract * @param _requestId the ID of the ChainLink request * @param _chainlinkResponseUint256 response object from Chainlink Oracles */ function fulfillSLI(bytes32 _requestId, uint256 _chainlinkResponseUint256) external virtual; /** * @dev gets the messenger precision */ function messengerPrecision() external view virtual returns (uint256); /** * @dev gets the slaRegistryAddress */ function slaRegistryAddress() external view virtual returns (address); /** * @dev gets the chainlink oracle contract address */ function oracle() external view virtual returns (address); /** * @dev gets the chainlink job id */ function jobId() external view virtual returns (bytes32); /** * @dev gets the fee amount of LINK token */ function fee() external view virtual returns (uint256); /** * @dev returns the requestsCounter */ function requestsCounter() external view virtual returns (uint256); /** * @dev returns the fulfillsCounter */ function fulfillsCounter() external view virtual returns (uint256); } pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../../StringUtils.sol"; import "../../PeriodRegistry.sol"; import "../../StakeRegistry.sol"; /** * @title NetworkAnalytics * @dev contract to get the network analytics for the staking efficiency use case */ contract NetworkAnalytics is Ownable, ChainlinkClient, ReentrancyGuard { using SafeERC20 for ERC20; struct AnalyticsRequest { bytes32 networkName; uint256 periodId; PeriodRegistry.PeriodType periodType; } /// @dev Period registry PeriodRegistry private periodRegistry; /// @dev StakeRegistry StakeRegistry private stakeRegistry; /// @dev bytes32 to store the available network names bytes32[] public networkNames; /// @dev (networkName=>periodType=>periodId=>bytes32) to store ipfsHash of the analytics corresponding to periodId mapping(bytes32 => mapping(PeriodRegistry.PeriodType => mapping(uint256 => bytes32))) public periodAnalytics; /// @dev (networkName=>periodType=>periodId=>bool) to state if a network-periodType-periodId was already requested mapping(bytes32 => mapping(PeriodRegistry.PeriodType => mapping(uint256 => bool))) public periodAnalyticsRequested; /// @dev Mapping that stores chainlink analytics request information mapping(bytes32 => AnalyticsRequest) public requestIdToAnalyticsRequest; /// @dev Array with all request IDs bytes32[] public requests; /// @dev Chainlink oracle address address private oracle; /// @dev chainlink jobId bytes32 private jobId; /// @dev fee for Chainlink querys. Currently 0.1 LINK uint256 private baseFee = 0.1 ether; /// @dev fee for Chainlink querys. Currently 0.1 LINK uint256 public fee; /** * @dev event emitted when modifying the callerReward * @param owner 1. - * @param newValue 2. - */ event CallerRewardModified(address indexed owner, uint256 newValue); /** * @dev event emitted when modifying the jobId * @param owner 1. - * @param jobId 2. - * @param fee 3. - */ event JobIdModified(address indexed owner, bytes32 jobId, uint256 fee); /** * @dev event emitted when having a response from Chainlink with the SLI * @param networkName 1. network name * @param periodType 2. id of the period * @param periodId 3. id of the period * @param ipfsHash 4. hash of the ipfs object */ event AnalyticsReceived( bytes32 networkName, PeriodRegistry.PeriodType periodType, uint256 periodId, bytes32 ipfsHash ); /** * @dev parameterize the variables according to network * @notice sets the Chainlink parameters (oracle address, token address, jobId) and sets the SLARegistry to 0x0 address * @param _chainlinkOracle 1. the address of the oracle to create requests to * @param _chainlinkToken 2. the address of LINK token contract * @param _jobId 3. the job id for the HTTPGet job * @param _periodRegistry 4. period registry * @param _stakeRegistry 5. stake registry * @param _feeMultiplier 6. states the amount of paid nodes running behind the precoordinator, to set the fee */ constructor( address _chainlinkOracle, address _chainlinkToken, bytes32 _jobId, PeriodRegistry _periodRegistry, StakeRegistry _stakeRegistry, uint256 _feeMultiplier ) public { jobId = _jobId; setChainlinkToken(_chainlinkToken); oracle = _chainlinkOracle; periodRegistry = _periodRegistry; stakeRegistry = _stakeRegistry; fee = _feeMultiplier.mul(baseFee); } function isValidNetwork(bytes32 _networkName) public view returns (bool) { for (uint256 index; index < networkNames.length; index++) { if (networkNames[index] == _networkName) return true; } return false; } /** * @dev function to add a valid network name * @param _networkName 1. bytes32 network name */ function addNetwork(bytes32 _networkName) external onlyOwner returns (bool) { require( isValidNetwork(_networkName) == false, "Network name already registered" ); networkNames.push(_networkName); return false; } /** * @dev function to add multiple valid network names * @param _networkNames 1. bytes32[] network names */ function addMultipleNetworks(bytes32[] calldata _networkNames) external onlyOwner returns (bool) { for (uint256 index = 0; index < _networkNames.length; index++) { if (!isValidNetwork(_networkNames[index])) { networkNames.push(_networkNames[index]); } } return false; } /** * @dev Request analytics object for the current period. * @param _periodId 1. id of the canonical period to be analyzed * @param _periodType 2. type of period to be queried * @param _networkName 3. network name to publish analytics * @param _ownerApproval 4. used to choose if the call is going to be funded by the contract owner, to avoid a block by contract owner */ function requestAnalytics( uint256 _periodId, PeriodRegistry.PeriodType _periodType, bytes32 _networkName, bool _ownerApproval ) public nonReentrant { require(isValidNetwork(_networkName), "Invalid network name"); bool periodIsFinished = periodRegistry.periodIsFinished(_periodType, _periodId); require(periodIsFinished == true, "Period has not finished yet"); require( periodAnalyticsRequested[_networkName][_periodType][_periodId] == false, "Analytics already requested" ); if (_ownerApproval) { ERC20(chainlinkTokenAddress()).safeTransferFrom( owner(), address(this), fee ); } else { ERC20(chainlinkTokenAddress()).safeTransferFrom( msg.sender, address(this), fee ); } Chainlink.Request memory request = buildChainlinkRequest( jobId, address(this), this.fulFillAnalytics.selector ); (uint256 start, uint256 end) = periodRegistry.getPeriodStartAndEnd(_periodType, _periodId); request.add("job_type", "staking_efficiency_analytics"); request.add("network_name", StringUtils.bytes32ToStr(_networkName)); request.add("period_id", StringUtils.uintToStr(_periodId)); request.add( "period_type", StringUtils.uintToStr(uint256(uint8(_periodType))) ); request.add("sla_monitoring_start", StringUtils.uintToStr(start)); request.add("sla_monitoring_end", StringUtils.uintToStr(end)); bytes32 requestId = sendChainlinkRequestTo(oracle, request, fee); requests.push(requestId); requestIdToAnalyticsRequest[requestId] = AnalyticsRequest({ networkName: _networkName, periodId: _periodId, periodType: _periodType }); periodAnalyticsRequested[_networkName][_periodType][_periodId] = true; } /** * @dev callback function for the Chainlink SLI request which stores * the SLI in the SLA contract * @param _requestId the ID of the ChainLink request * @param _chainlinkResponse response object from Chainlink Oracles */ function fulFillAnalytics(bytes32 _requestId, bytes32 _chainlinkResponse) external recordChainlinkFulfillment(_requestId) nonReentrant { AnalyticsRequest memory request = requestIdToAnalyticsRequest[_requestId]; emit AnalyticsReceived( request.networkName, request.periodType, request.periodId, _chainlinkResponse ); periodAnalytics[request.networkName][request.periodType][ request.periodId ] = _chainlinkResponse; } /** * @dev sets a new jobId, which is a agreement Id of a PreCoordinator contract * @param _jobId the id of the PreCoordinator agreement * @param _feeMultiplier how many Chainlink nodes would be paid on the agreement id, to set the fee value */ function setChainlinkJobID(bytes32 _jobId, uint256 _feeMultiplier) external onlyOwner { jobId = _jobId; fee = _feeMultiplier.mul(baseFee); emit JobIdModified(msg.sender, _jobId, fee); } function getNetworkNames() external view returns (bytes32[] memory networks) { networks = networkNames; } } pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol"; import "../../SLA.sol"; import "../../PeriodRegistry.sol"; import "../../StringUtils.sol"; import "./NetworkAnalytics.sol"; import "../../messenger/IMessenger.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title SEMessenger * @dev Staking efficiency Messenger */ contract SEMessenger is ChainlinkClient, IMessenger, ReentrancyGuard { using SafeERC20 for ERC20; /// @dev Mapping that stores chainlink sli request information mapping(bytes32 => SLIRequest) public requestIdToSLIRequest; /// @dev Array with all request IDs bytes32[] public requests; /// @dev The address of the SLARegistry contract address private _slaRegistryAddress; /// @dev Network analytics contract address address public immutable networkAnalyticsAddress; /// @dev Chainlink oracle address address private immutable _oracle; /// @dev chainlink jobId bytes32 private _jobId; // @dev fee for Chainlink querys. Currently 0.1 LINK uint256 private constant _baseFee = 0.1 ether; /// @dev fee for Chainlink querys. Currently 0.1 LINK uint256 private _fee; /// @dev to multiply the SLI value and get better precision. Useful to deploy SLO correctly uint256 private constant _messengerPrecision = 10**3; uint256 private _requestsCounter; uint256 private _fulfillsCounter; /** * @dev parameterize the variables according to network * @notice sets the Chainlink parameters (oracle address, token address, jobId) and sets the SLARegistry to 0x0 address * @param _messengerChainlinkOracle 1. the address of the oracle to create requests to * @param _messengerChainlinkToken 2. the address of LINK token contract * @param _messengerJobId 3. the job id for Staking efficiency job * @param _networkAnalyticsAddress 4. Network analytics contract address * @param _feeMultiplier 6. states the amount of paid nodes running behind the precoordinator, to set the fee */ constructor( address _messengerChainlinkOracle, address _messengerChainlinkToken, bytes32 _messengerJobId, address _networkAnalyticsAddress, uint256 _feeMultiplier ) public { _jobId = _messengerJobId; setChainlinkToken(_messengerChainlinkToken); _oracle = _messengerChainlinkOracle; networkAnalyticsAddress = _networkAnalyticsAddress; _fee = _feeMultiplier * _baseFee; } /** * @dev event emitted when modifying the jobId * @param owner 1. - * @param jobId 2. - * @param fee 3. - */ event JobIdModified(address indexed owner, bytes32 jobId, uint256 fee); /** * @dev event emitted when modifying the jobId * @param caller 1. - * @param requestsCounter 2. - * @param requestId 3. - */ event SLIRequested( address indexed caller, uint256 requestsCounter, bytes32 requestId ); /// @dev Throws if called by any address other than the SLARegistry contract or Chainlink Oracle. modifier onlySLARegistry() { require( msg.sender == _slaRegistryAddress, "Can only be called by SLARegistry" ); _; } /** * @dev sets the SLARegistry contract address and can only be called * once */ function setSLARegistry() public override { // Only able to trigger this function once require( _slaRegistryAddress == address(0), "SLARegistry address has already been set" ); _slaRegistryAddress = msg.sender; } /** * @dev creates a ChainLink request to get a new SLI value for the * given params. Can only be called by the SLARegistry contract or Chainlink Oracle. * @param _periodId 1. value of the period id * @param _slaAddress 2. SLA Address * @param _messengerOwnerApproval 3. if approval by owner or msg sender */ function requestSLI( uint256 _periodId, address _slaAddress, bool _messengerOwnerApproval, address _callerAddress ) public override onlySLARegistry nonReentrant { SLA sla = SLA(_slaAddress); PeriodRegistry.PeriodType periodType = sla.periodType(); // extraData[0] is the networkName for StakingEfficiency use case bytes32 networkName = sla.extraData(0); bytes32 ipfsAnalytics = NetworkAnalytics(networkAnalyticsAddress).periodAnalytics( networkName, periodType, _periodId ); require( ipfsAnalytics != 0, "Network analytics object is not assigned yet" ); if (_messengerOwnerApproval) { ERC20(chainlinkTokenAddress()).safeTransferFrom( owner(), address(this), _fee ); } else { ERC20(chainlinkTokenAddress()).safeTransferFrom( _callerAddress, address(this), _fee ); } Chainlink.Request memory request = buildChainlinkRequest( _jobId, address(this), this.fulfillSLI.selector ); request.add("job_type", "staking_efficiency"); request.add("period_id", StringUtils.uintToStr(_periodId)); request.add("sla_address", StringUtils.addressToString(_slaAddress)); request.add( "network_analytics_address", StringUtils.addressToString(networkAnalyticsAddress) ); // Sends the request with 0.1 LINK to the oracle contract bytes32 requestId = sendChainlinkRequestTo(_oracle, request, _fee); requests.push(requestId); requestIdToSLIRequest[requestId] = SLIRequest({ slaAddress: _slaAddress, periodId: _periodId }); _requestsCounter += 1; emit SLIRequested(_callerAddress, _requestsCounter, requestId); } /** * @dev callback function for the Chainlink SLI request which stores * the SLI in the SLA contract * @param _requestId the ID of the ChainLink request * @param _chainlinkResponseUint256 response object from Chainlink Oracles */ function fulfillSLI(bytes32 _requestId, uint256 _chainlinkResponseUint256) external override nonReentrant recordChainlinkFulfillment(_requestId) { bytes32 _chainlinkResponse = bytes32(_chainlinkResponseUint256); SLIRequest memory request = requestIdToSLIRequest[_requestId]; emit SLIReceived( request.slaAddress, request.periodId, _requestId, _chainlinkResponse ); (uint256 hits, uint256 misses) = parseSLIData(_chainlinkResponse); uint256 total = hits.add(misses); uint256 stakingEfficiency = hits.mul(100 * _messengerPrecision).div(total); SLA(request.slaAddress).registerSLI( stakingEfficiency, request.periodId ); _fulfillsCounter += 1; } /** * @dev recieves a string of "hits,misses" data and returns hits and misses as uint256 * @param sliData the ID of the ChainLink request */ function parseSLIData(bytes32 sliData) public pure returns (uint256, uint256) { bytes memory bytesSLIData = bytes(StringUtils.bytes32ToStr(sliData)); uint256 sliDataLength = bytesSLIData.length; bytes memory bytesHits = new bytes(sliDataLength); bytes memory bytesMisses = new bytes(sliDataLength); for (uint256 index; index < sliDataLength; index++) { if (bytesSLIData[index] == bytes1(",")) { for (uint256 index2 = 0; index2 < index; index2++) { bytesHits[index2] = bytesSLIData[index2]; } for ( uint256 index3 = 0; index3 < sliDataLength - index - 1; index3++ ) { bytesMisses[index3] = bytesSLIData[index + 1 + index3]; } } } uint256 hits = StringUtils.bytesToUint(bytesHits); uint256 misses = StringUtils.bytesToUint(bytesMisses); return (hits, misses); } /** * @dev sets a new jobId, which is a agreement Id of a PreCoordinator contract * @param _newJobId the id of the PreCoordinator agreement * @param _feeMultiplier how many Chainlink nodes would be paid on the agreement id, to set the fee value */ function setChainlinkJobID(bytes32 _newJobId, uint256 _feeMultiplier) external onlyOwner { _jobId = _newJobId; _fee = _feeMultiplier * _baseFee; emit JobIdModified(msg.sender, _newJobId, _fee); } /** * @dev returns the value of the sla registry address */ function slaRegistryAddress() external view override returns (address) { return _slaRegistryAddress; } /** * @dev returns the value of the messenger precision */ function messengerPrecision() external view override returns (uint256) { return _messengerPrecision; } /** * @dev returns the chainlink oracle contract address */ function oracle() external view override returns (address) { return _oracle; } /** * @dev returns the chainlink job id */ function jobId() external view override returns (bytes32) { return _jobId; } /** * @dev returns the chainlink fee value on LINK tokens */ function fee() external view override returns (uint256) { return _fee; } /** * @dev returns the requestsCounter */ function requestsCounter() external view override returns (uint256) { return _requestsCounter; } /** * @dev returns the fulfillsCounter */ function fulfillsCounter() external view override returns (uint256) { return _fulfillsCounter; } } pragma solidity ^0.6.0; import { CBORChainlink } from "./vendor/CBORChainlink.sol"; import { BufferChainlink } from "./vendor/BufferChainlink.sol"; /** * @title Library for common Chainlink functions * @dev Uses imported CBOR library for encoding to buffer */ library Chainlink { uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase using CBORChainlink for BufferChainlink.buffer; struct Request { bytes32 id; address callbackAddress; bytes4 callbackFunctionId; uint256 nonce; BufferChainlink.buffer buf; } /** * @notice Initializes a Chainlink request * @dev Sets the ID, callback address, and callback function signature on the request * @param self The uninitialized request * @param _id The Job Specification ID * @param _callbackAddress The callback address * @param _callbackFunction The callback function signature * @return The initialized request */ function initialize( Request memory self, bytes32 _id, address _callbackAddress, bytes4 _callbackFunction ) internal pure returns (Chainlink.Request memory) { BufferChainlink.init(self.buf, defaultBufferSize); self.id = _id; self.callbackAddress = _callbackAddress; self.callbackFunctionId = _callbackFunction; return self; } /** * @notice Sets the data for the buffer without encoding CBOR on-chain * @dev CBOR can be closed with curly-brackets {} or they can be left off * @param self The initialized request * @param _data The CBOR data */ function setBuffer(Request memory self, bytes memory _data) internal pure { BufferChainlink.init(self.buf, _data.length); BufferChainlink.append(self.buf, _data); } /** * @notice Adds a string value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The string value to add */ function add(Request memory self, string memory _key, string memory _value) internal pure { self.buf.encodeString(_key); self.buf.encodeString(_value); } /** * @notice Adds a bytes value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The bytes value to add */ function addBytes(Request memory self, string memory _key, bytes memory _value) internal pure { self.buf.encodeString(_key); self.buf.encodeBytes(_value); } /** * @notice Adds a int256 value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The int256 value to add */ function addInt(Request memory self, string memory _key, int256 _value) internal pure { self.buf.encodeString(_key); self.buf.encodeInt(_value); } /** * @notice Adds a uint256 value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The uint256 value to add */ function addUint(Request memory self, string memory _key, uint256 _value) internal pure { self.buf.encodeString(_key); self.buf.encodeUInt(_value); } /** * @notice Adds an array of strings to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _values The array of string values to add */ function addStringArray(Request memory self, string memory _key, string[] memory _values) internal pure { self.buf.encodeString(_key); self.buf.startArray(); for (uint256 i = 0; i < _values.length; i++) { self.buf.encodeString(_values[i]); } self.buf.endSequence(); } } pragma solidity ^0.6.0; import "./Chainlink.sol"; import "./interfaces/ENSInterface.sol"; import "./interfaces/LinkTokenInterface.sol"; import "./interfaces/ChainlinkRequestInterface.sol"; import "./interfaces/PointerInterface.sol"; import { ENSResolver as ENSResolver_Chainlink } from "./vendor/ENSResolver.sol"; import "./vendor/SafeMathChainlink.sol"; /** * @title The ChainlinkClient contract * @notice Contract writers can inherit this contract in order to create requests for the * Chainlink network */ contract ChainlinkClient { using Chainlink for Chainlink.Request; using SafeMathChainlink for uint256; uint256 constant internal LINK = 10**18; uint256 constant private AMOUNT_OVERRIDE = 0; address constant private SENDER_OVERRIDE = address(0); uint256 constant private ARGS_VERSION = 1; bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link"); bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle"); address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571; ENSInterface private ens; bytes32 private ensNode; LinkTokenInterface private link; ChainlinkRequestInterface private oracle; uint256 private requestCount = 1; mapping(bytes32 => address) private pendingRequests; event ChainlinkRequested(bytes32 indexed id); event ChainlinkFulfilled(bytes32 indexed id); event ChainlinkCancelled(bytes32 indexed id); /** * @notice Creates a request that can hold additional parameters * @param _specId The Job Specification ID that the request will be created for * @param _callbackAddress The callback address that the response will be sent to * @param _callbackFunctionSignature The callback function signature to use for the callback address * @return A Chainlink Request struct in memory */ function buildChainlinkRequest( bytes32 _specId, address _callbackAddress, bytes4 _callbackFunctionSignature ) internal pure returns (Chainlink.Request memory) { Chainlink.Request memory req; return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature); } /** * @notice Creates a Chainlink request to the stored oracle address * @dev Calls `chainlinkRequestTo` with the stored oracle address * @param _req The initialized Chainlink Request * @param _payment The amount of LINK to send for the request * @return requestId The request ID */ function sendChainlinkRequest(Chainlink.Request memory _req, uint256 _payment) internal returns (bytes32) { return sendChainlinkRequestTo(address(oracle), _req, _payment); } /** * @notice Creates a Chainlink request to the specified oracle address * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to * send LINK which creates a request on the target oracle contract. * Emits ChainlinkRequested event. * @param _oracle The address of the oracle for the request * @param _req The initialized Chainlink Request * @param _payment The amount of LINK to send for the request * @return requestId The request ID */ function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment) internal returns (bytes32 requestId) { requestId = keccak256(abi.encodePacked(this, requestCount)); _req.nonce = requestCount; pendingRequests[requestId] = _oracle; emit ChainlinkRequested(requestId); require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle"); requestCount += 1; return requestId; } /** * @notice Allows a request to be cancelled if it has not been fulfilled * @dev Requires keeping track of the expiration value emitted from the oracle contract. * Deletes the request from the `pendingRequests` mapping. * Emits ChainlinkCancelled event. * @param _requestId The request ID * @param _payment The amount of LINK sent for the request * @param _callbackFunc The callback function specified for the request * @param _expiration The time of the expiration for the request */ function cancelChainlinkRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) internal { ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]); delete pendingRequests[_requestId]; emit ChainlinkCancelled(_requestId); requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration); } /** * @notice Sets the stored oracle address * @param _oracle The address of the oracle contract */ function setChainlinkOracle(address _oracle) internal { oracle = ChainlinkRequestInterface(_oracle); } /** * @notice Sets the LINK token address * @param _link The address of the LINK token contract */ function setChainlinkToken(address _link) internal { link = LinkTokenInterface(_link); } /** * @notice Sets the Chainlink token address for the public * network as given by the Pointer contract */ function setPublicChainlinkToken() internal { setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress()); } /** * @notice Retrieves the stored address of the LINK token * @return The address of the LINK token */ function chainlinkTokenAddress() internal view returns (address) { return address(link); } /** * @notice Retrieves the stored address of the oracle contract * @return The address of the oracle contract */ function chainlinkOracleAddress() internal view returns (address) { return address(oracle); } /** * @notice Allows for a request which was created on another contract to be fulfilled * on this contract * @param _oracle The address of the oracle contract that will fulfill the request * @param _requestId The request ID used for the response */ function addChainlinkExternalRequest(address _oracle, bytes32 _requestId) internal notPendingRequest(_requestId) { pendingRequests[_requestId] = _oracle; } /** * @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS * @dev Accounts for subnodes having different resolvers * @param _ens The address of the ENS contract * @param _node The ENS node hash */ function useChainlinkWithENS(address _ens, bytes32 _node) internal { ens = ENSInterface(_ens); ensNode = _node; bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(linkSubnode)); setChainlinkToken(resolver.addr(linkSubnode)); updateChainlinkOracleWithENS(); } /** * @notice Sets the stored oracle contract with the address resolved by ENS * @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously */ function updateChainlinkOracleWithENS() internal { bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(oracleSubnode)); setChainlinkOracle(resolver.addr(oracleSubnode)); } /** * @notice Encodes the request to be sent to the oracle contract * @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types * will be validated in the oracle contract. * @param _req The initialized Chainlink Request * @return The bytes payload for the `transferAndCall` method */ function encodeRequest(Chainlink.Request memory _req) private view returns (bytes memory) { return abi.encodeWithSelector( oracle.oracleRequest.selector, SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent _req.id, _req.callbackAddress, _req.callbackFunctionId, _req.nonce, ARGS_VERSION, _req.buf.buf); } /** * @notice Ensures that the fulfillment is valid for this contract * @dev Use if the contract developer prefers methods instead of modifiers for validation * @param _requestId The request ID for fulfillment */ function validateChainlinkCallback(bytes32 _requestId) internal recordChainlinkFulfillment(_requestId) // solhint-disable-next-line no-empty-blocks {} /** * @dev Reverts if the sender is not the oracle of the request. * Emits ChainlinkFulfilled event. * @param _requestId The request ID for fulfillment */ modifier recordChainlinkFulfillment(bytes32 _requestId) { require(msg.sender == pendingRequests[_requestId], "Source must be the oracle of the request"); delete pendingRequests[_requestId]; emit ChainlinkFulfilled(_requestId); _; } /** * @dev Reverts if the request is already pending * @param _requestId The request ID for fulfillment */ modifier notPendingRequest(bytes32 _requestId) { require(pendingRequests[_requestId] == address(0), "Request is already pending"); _; } } pragma solidity ^0.6.0; interface ChainlinkRequestInterface { function oracleRequest( address sender, uint256 requestPrice, bytes32 serviceAgreementID, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, // Currently unused, always "1" bytes calldata data ) external; function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunctionId, uint256 expiration ) external; } pragma solidity ^0.6.0; interface ENSInterface { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address _owner) external; function setResolver(bytes32 node, address _resolver) external; function setOwner(bytes32 node, address _owner) external; function setTTL(bytes32 node, uint64 _ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } pragma solidity ^0.6.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } pragma solidity ^0.6.0; interface PointerInterface { function getAddress() external view returns (address); } pragma solidity ^0.6.0; /** * @dev A library for working with mutable byte buffers in Solidity. * * Byte buffers are mutable and expandable, and provide a variety of primitives * for writing to them. At any time you can fetch a bytes object containing the * current contents of the buffer. The bytes object should not be stored between * operations, as it may change due to resizing of the buffer. */ library BufferChainlink { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes(bytes memory b) internal pure returns(buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if (a > b) { return a; } return b; } /** * @dev Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate(buffer memory buf) internal pure returns (buffer memory) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint dest; uint src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } src := add(data, 32) } // 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)) } return buf; } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) { if (off >= buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chhaining. */ function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { return writeInt(buf, buf.buf.length, data, len); } } pragma solidity ^0.6.0; import { BufferChainlink } from "./BufferChainlink.sol"; library CBORChainlink { using BufferChainlink for BufferChainlink.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(BufferChainlink.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.appendUint8(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.appendUint8(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.appendUint8(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(BufferChainlink.buffer memory buf, uint8 major) private pure { buf.appendUint8(uint8((major << 5) | 31)); } function encodeUInt(BufferChainlink.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(BufferChainlink.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(BufferChainlink.buffer memory buf, bytes memory value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(BufferChainlink.buffer memory buf, string memory value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } pragma solidity ^0.6.0; abstract contract ENSResolver { function addr(bytes32 node) public view virtual returns (address); } 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 SafeMathChainlink { /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; 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; } } // 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; import "../access/AccessControl.sol"; import "../GSN/Context.sol"; import "../token/ERC20/ERC20.sol"; import "../token/ERC20/ERC20Burnable.sol"; import "../token/ERC20/ERC20Pausable.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // 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.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). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./ERC20.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // 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; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @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 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)); } } // SPDX-License-Identifier: MIT 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. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: 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; } }
@dev DSLA deposit by period to create SLA
uint256 private _dslaDepositByPeriod = 1000 ether;
1,570,548
[ 1, 3948, 2534, 443, 1724, 635, 3879, 358, 752, 348, 2534, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 389, 30249, 69, 758, 1724, 858, 5027, 273, 4336, 225, 2437, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.6; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@kyber.network/utils-sc/contracts/Utils.sol"; import "../IKyberFeeHandler.sol"; import "../IKyberDao.sol"; import "./WithdrawableNoModifiers.sol"; import "./IKyberNetwork.sol"; import "./IKyberReserve.sol"; import "./IKyberMatchingEngine.sol"; import "./IKyberStorage.sol"; import "./IGasHelper.sol"; /** * @title kyberNetwork main contract * Interacts with contracts: * kyberDao: to retrieve fee data * kyberFeeHandler: accumulates and distributes trade fees * kyberMatchingEngine: parse user hint and run reserve matching algorithm * kyberStorage: store / access reserves, token listings and contract addresses * kyberReserve(s): query rate and trade */ contract KyberNetwork is WithdrawableNoModifiers, Utils, IKyberNetwork, ReentrancyGuard { using SafeERC20 for IERC20Ext; struct NetworkFeeData { uint64 expiryTimestamp; uint16 feeBps; } /// @notice Stores work data for reserves (either for token -> eth, or eth -> token) /// @dev Variables are in-place, ie. reserve with addresses[i] has id of ids[i], offers rate of rates[i], etc. /// @param addresses List of reserve addresses selected for the trade /// @param ids List of reserve ids, to be used for KyberTrade event /// @param rates List of rates that were offered by the reserves /// @param isFeeAccountedFlags List of reserves requiring users to pay network fee /// @param isEntitledRebateFlags List of reserves eligible for rebates /// @param splitsBps List of proportions of trade amount allocated to the reserves. /// If there is only 1 reserve, then it should have a value of 10000 bps /// @param srcAmounts Source amount per reserve. /// @param decimals Token decimals. Src decimals when for src -> eth, dest decimals when eth -> dest struct ReservesData { IKyberReserve[] addresses; bytes32[] ids; uint256[] rates; bool[] isFeeAccountedFlags; bool[] isEntitledRebateFlags; uint256[] splitsBps; uint256[] srcAmounts; uint256 decimals; } /// @notice Main trade data structure, is initialised and used for the entire trade flow /// @param input Initialised when initTradeInput is called. Stores basic trade info /// @param tokenToEth Stores information about reserves that were selected for src -> eth side of trade /// @param ethToToken Stores information about reserves that were selected for eth -> dest side of trade /// @param tradeWei Trade amount in ether wei, before deducting fees. /// @param networkFeeWei Network fee in ether wei. For t2t trades, it can go up to 200% of networkFeeBps /// @param platformFeeWei Platform fee in ether wei /// @param networkFeeBps Network fee bps determined by kyberDao, or default value /// @param numEntitledRebateReserves No. of reserves that are eligible for rebates /// @param feeAccountedBps Proportion of this trade that fee is accounted to, in BPS. Up to 2 * BPS struct TradeData { TradeInput input; ReservesData tokenToEth; ReservesData ethToToken; uint256 tradeWei; uint256 networkFeeWei; uint256 platformFeeWei; uint256 networkFeeBps; uint256 numEntitledRebateReserves; uint256 feeAccountedBps; // what part of this trade is fee paying. for token -> token - up to 200% } struct TradeInput { address payable trader; IERC20Ext src; uint256 srcAmount; IERC20Ext dest; address payable destAddress; uint256 maxDestAmount; uint256 minConversionRate; address platformWallet; uint256 platformFeeBps; } uint256 internal constant PERM_HINT_GET_RATE = 1 << 255; // for backwards compatibility uint256 internal constant DEFAULT_NETWORK_FEE_BPS = 25; // till we read value from kyberDao uint256 internal constant MAX_APPROVED_PROXIES = 2; // limit number of proxies that can trade here IKyberFeeHandler internal kyberFeeHandler; IKyberDao internal kyberDao; IKyberMatchingEngine internal kyberMatchingEngine; IKyberStorage internal kyberStorage; IGasHelper internal gasHelper; NetworkFeeData internal networkFeeData; // data is feeBps and expiry timestamp uint256 internal maxGasPriceValue = 50 * 1000 * 1000 * 1000; // 50 gwei bool internal isEnabled = false; // is network enabled mapping(address => bool) internal kyberProxyContracts; event EtherReceival(address indexed sender, uint256 amount); event KyberFeeHandlerUpdated(IKyberFeeHandler newKyberFeeHandler); event KyberMatchingEngineUpdated(IKyberMatchingEngine newKyberMatchingEngine); event GasHelperUpdated(IGasHelper newGasHelper); event KyberDaoUpdated(IKyberDao newKyberDao); event KyberNetworkParamsSet(uint256 maxGasPrice, uint256 negligibleRateDiffBps); event KyberNetworkSetEnable(bool isEnabled); event KyberProxyAdded(address kyberProxy); event KyberProxyRemoved(address kyberProxy); event ListedReservesForToken( IERC20Ext indexed token, address[] reserves, bool add ); constructor(address _admin, IKyberStorage _kyberStorage) public WithdrawableNoModifiers(_admin) { updateNetworkFee(now, DEFAULT_NETWORK_FEE_BPS); kyberStorage = _kyberStorage; } receive() external payable { emit EtherReceival(msg.sender, msg.value); } /// @notice Backward compatible function /// @notice Use token address ETH_TOKEN_ADDRESS for ether /// @dev Trade from src to dest token and sends dest token to destAddress /// @param trader Address of the taker side of this trade /// @param src Source token /// @param srcAmount Amount of src tokens in twei /// @param dest Destination token /// @param destAddress Address to send tokens to /// @param maxDestAmount A limit on the amount of dest tokens in twei /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade reverts /// @param walletId Platform wallet address for receiving fees /// @param hint Advanced instructions for running the trade /// @return destAmount Amount of actual dest tokens in twei function tradeWithHint( address payable trader, IERC20Ext src, uint256 srcAmount, IERC20Ext dest, address payable destAddress, uint256 maxDestAmount, uint256 minConversionRate, address payable walletId, bytes calldata hint ) external payable returns (uint256 destAmount) { TradeData memory tradeData = initTradeInput({ trader: trader, src: src, dest: dest, srcAmount: srcAmount, destAddress: destAddress, maxDestAmount: maxDestAmount, minConversionRate: minConversionRate, platformWallet: walletId, platformFeeBps: 0 }); return trade(tradeData, hint); } /// @notice Use token address ETH_TOKEN_ADDRESS for ether /// @dev Trade from src to dest token and sends dest token to destAddress /// @param trader Address of the taker side of this trade /// @param src Source token /// @param srcAmount Amount of src tokens in twei /// @param dest Destination token /// @param destAddress Address to send tokens to /// @param maxDestAmount A limit on the amount of dest tokens in twei /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade reverts /// @param platformWallet Platform wallet address for receiving fees /// @param platformFeeBps Part of the trade that is allocated as fee to platform wallet. Ex: 1000 = 10% /// @param hint Advanced instructions for running the trade /// @return destAmount Amount of actual dest tokens in twei function tradeWithHintAndFee( address payable trader, IERC20Ext src, uint256 srcAmount, IERC20Ext dest, address payable destAddress, uint256 maxDestAmount, uint256 minConversionRate, address payable platformWallet, uint256 platformFeeBps, bytes calldata hint ) external payable override returns (uint256 destAmount) { TradeData memory tradeData = initTradeInput({ trader: trader, src: src, dest: dest, srcAmount: srcAmount, destAddress: destAddress, maxDestAmount: maxDestAmount, minConversionRate: minConversionRate, platformWallet: platformWallet, platformFeeBps: platformFeeBps }); return trade(tradeData, hint); } /// @notice Can be called only by kyberStorage /// @dev Allow or prevent to trade token -> eth for a reserve /// @param reserve The reserve address /// @param token Token address /// @param add If true, then give reserve token allowance, otherwise set zero allowance function listTokenForReserve( address reserve, IERC20Ext token, bool add ) external override { require(msg.sender == address(kyberStorage), "only kyberStorage"); if (add) { token.safeApprove(reserve, MAX_ALLOWANCE); getSetDecimals(token); } else { token.safeApprove(reserve, 0); } } /// @notice Can be called only by operator /// @dev Allow or prevent to trade token -> eth for list of reserves /// Useful for migration to new network contract /// Call storage to get list of reserves supporting token -> eth /// @param token Token address /// @param startIndex start index in reserves list /// @param endIndex end index in reserves list (can be larger) /// @param add If true, then give reserve token allowance, otherwise set zero allowance function listReservesForToken( IERC20Ext token, uint256 startIndex, uint256 endIndex, bool add ) external { onlyOperator(); if (startIndex > endIndex) { // no need to do anything return; } address[] memory reserves = kyberStorage.getReserveAddressesPerTokenSrc( token, startIndex, endIndex ); if (reserves.length == 0) { // no need to do anything return; } for(uint i = 0; i < reserves.length; i++) { if (add) { token.safeApprove(reserves[i], MAX_ALLOWANCE); getSetDecimals(token); } else { token.safeApprove(reserves[i], 0); } } emit ListedReservesForToken(token, reserves, add); } function setContracts( IKyberFeeHandler _kyberFeeHandler, IKyberMatchingEngine _kyberMatchingEngine, IGasHelper _gasHelper ) external virtual { onlyAdmin(); if (kyberFeeHandler != _kyberFeeHandler) { kyberFeeHandler = _kyberFeeHandler; emit KyberFeeHandlerUpdated(_kyberFeeHandler); } if (kyberMatchingEngine != _kyberMatchingEngine) { kyberMatchingEngine = _kyberMatchingEngine; emit KyberMatchingEngineUpdated(_kyberMatchingEngine); } if ((_gasHelper != IGasHelper(0)) && (_gasHelper != gasHelper)) { gasHelper = _gasHelper; emit GasHelperUpdated(_gasHelper); } kyberStorage.setContracts(address(_kyberFeeHandler), address(_kyberMatchingEngine)); require(_kyberFeeHandler != IKyberFeeHandler(0)); require(_kyberMatchingEngine != IKyberMatchingEngine(0)); } function setKyberDaoContract(IKyberDao _kyberDao) external { // enable setting null kyberDao address onlyAdmin(); if (kyberDao != _kyberDao) { kyberDao = _kyberDao; kyberStorage.setKyberDaoContract(address(_kyberDao)); emit KyberDaoUpdated(_kyberDao); } } function setParams(uint256 _maxGasPrice, uint256 _negligibleRateDiffBps) external { onlyAdmin(); maxGasPriceValue = _maxGasPrice; kyberMatchingEngine.setNegligibleRateDiffBps(_negligibleRateDiffBps); emit KyberNetworkParamsSet(maxGasPriceValue, _negligibleRateDiffBps); } function setEnable(bool enable) external { onlyAdmin(); if (enable) { require(kyberFeeHandler != IKyberFeeHandler(0)); require(kyberMatchingEngine != IKyberMatchingEngine(0)); require(kyberStorage.isKyberProxyAdded()); } isEnabled = enable; emit KyberNetworkSetEnable(isEnabled); } /// @dev No. of kyberProxies is capped function addKyberProxy(address kyberProxy) external virtual { onlyAdmin(); kyberStorage.addKyberProxy(kyberProxy, MAX_APPROVED_PROXIES); require(kyberProxy != address(0)); require(!kyberProxyContracts[kyberProxy]); kyberProxyContracts[kyberProxy] = true; emit KyberProxyAdded(kyberProxy); } function removeKyberProxy(address kyberProxy) external virtual { onlyAdmin(); kyberStorage.removeKyberProxy(kyberProxy); require(kyberProxyContracts[kyberProxy]); kyberProxyContracts[kyberProxy] = false; emit KyberProxyRemoved(kyberProxy); } /// @dev gets the expected rates when trading src -> dest token, with / without fees /// @param src Source token /// @param dest Destination token /// @param srcQty Amount of src tokens in twei /// @param platformFeeBps Part of the trade that is allocated as fee to platform wallet. Ex: 1000 = 10% /// @param hint Advanced instructions for running the trade /// @return rateWithNetworkFee Rate after deducting network fee but excluding platform fee /// @return rateWithAllFees = actual rate. Rate after accounting for both network and platform fees function getExpectedRateWithHintAndFee( IERC20Ext src, IERC20Ext dest, uint256 srcQty, uint256 platformFeeBps, bytes calldata hint ) external view override returns ( uint256 rateWithNetworkFee, uint256 rateWithAllFees ) { if (src == dest) return (0, 0); TradeData memory tradeData = initTradeInput({ trader: payable(address(0)), src: src, dest: dest, srcAmount: (srcQty == 0) ? 1 : srcQty, destAddress: payable(address(0)), maxDestAmount: 2**255, minConversionRate: 0, platformWallet: payable(address(0)), platformFeeBps: platformFeeBps }); tradeData.networkFeeBps = getNetworkFee(); uint256 destAmount; (destAmount, rateWithNetworkFee) = calcRatesAndAmounts(tradeData, hint); rateWithAllFees = calcRateFromQty( tradeData.input.srcAmount, destAmount, tradeData.tokenToEth.decimals, tradeData.ethToToken.decimals ); } /// @notice Backward compatible API /// @dev Gets the expected and slippage rate for exchanging src -> dest token /// @dev worstRate is hardcoded to be 3% lower of expectedRate /// @param src Source token /// @param dest Destination token /// @param srcQty Amount of src tokens in twei /// @return expectedRate for a trade after deducting network fee. /// @return worstRate for a trade. Calculated to be expectedRate * 97 / 100 function getExpectedRate( IERC20Ext src, IERC20Ext dest, uint256 srcQty ) external view returns (uint256 expectedRate, uint256 worstRate) { if (src == dest) return (0, 0); uint256 qty = srcQty & ~PERM_HINT_GET_RATE; TradeData memory tradeData = initTradeInput({ trader: payable(address(0)), src: src, dest: dest, srcAmount: (qty == 0) ? 1 : qty, destAddress: payable(address(0)), maxDestAmount: 2**255, minConversionRate: 0, platformWallet: payable(address(0)), platformFeeBps: 0 }); tradeData.networkFeeBps = getNetworkFee(); (, expectedRate) = calcRatesAndAmounts(tradeData, ""); worstRate = (expectedRate * 97) / 100; // backward compatible formula } /// @notice Returns some data about the network /// @param negligibleDiffBps Negligible rate difference (in basis pts) when searching best rate /// @param networkFeeBps Network fees to be charged (in basis pts) /// @param expiryTimestamp Timestamp for which networkFeeBps will expire, /// and needs to be updated by calling kyberDao contract / set to default function getNetworkData() external view override returns ( uint256 negligibleDiffBps, uint256 networkFeeBps, uint256 expiryTimestamp ) { (networkFeeBps, expiryTimestamp) = readNetworkFeeData(); negligibleDiffBps = kyberMatchingEngine.getNegligibleRateDiffBps(); return (negligibleDiffBps, networkFeeBps, expiryTimestamp); } function getContracts() external view returns ( IKyberFeeHandler kyberFeeHandlerAddress, IKyberDao kyberDaoAddress, IKyberMatchingEngine kyberMatchingEngineAddress, IKyberStorage kyberStorageAddress, IGasHelper gasHelperAddress, IKyberNetworkProxy[] memory kyberProxyAddresses ) { return ( kyberFeeHandler, kyberDao, kyberMatchingEngine, kyberStorage, gasHelper, kyberStorage.getKyberProxies() ); } /// @notice returns the max gas price allowable for trades function maxGasPrice() external view override returns (uint256) { return maxGasPriceValue; } /// @notice returns status of the network. If disabled, trades cannot happen. function enabled() external view override returns (bool) { return isEnabled; } /// @notice Gets network fee from the kyberDao (or use default). /// For trade function, so that data can be updated and cached. /// @dev Note that this function can be triggered by anyone, so that /// the first trader of a new epoch can avoid incurring extra gas costs function getAndUpdateNetworkFee() public returns (uint256 networkFeeBps) { uint256 expiryTimestamp; (networkFeeBps, expiryTimestamp) = readNetworkFeeData(); if (expiryTimestamp < now && kyberDao != IKyberDao(0)) { (networkFeeBps, expiryTimestamp) = kyberDao.getLatestNetworkFeeDataWithCache(); updateNetworkFee(expiryTimestamp, networkFeeBps); } } /// @notice Calculates platform fee and reserve rebate percentages for the trade. /// Transfers eth and rebate wallet data to kyberFeeHandler function handleFees(TradeData memory tradeData) internal { uint256 sentFee = tradeData.networkFeeWei + tradeData.platformFeeWei; //no need to handle fees if total fee is zero if (sentFee == 0) return; // update reserve eligibility and rebate percentages ( address[] memory rebateWallets, uint256[] memory rebatePercentBps ) = calculateRebates(tradeData); // send total fee amount to fee handler with reserve data kyberFeeHandler.handleFees{value: sentFee}( ETH_TOKEN_ADDRESS, rebateWallets, rebatePercentBps, tradeData.input.platformWallet, tradeData.platformFeeWei, tradeData.networkFeeWei ); } function updateNetworkFee(uint256 expiryTimestamp, uint256 feeBps) internal { require(expiryTimestamp < 2**64, "expiry overflow"); require(feeBps < BPS / 2, "fees exceed BPS"); networkFeeData.expiryTimestamp = uint64(expiryTimestamp); networkFeeData.feeBps = uint16(feeBps); } /// @notice Use token address ETH_TOKEN_ADDRESS for ether /// @dev Do one trade with each reserve in reservesData, verifying network balance /// as expected to ensure reserves take correct src amount /// @param src Source token /// @param dest Destination token /// @param destAddress Address to send tokens to /// @param reservesData reservesData to trade /// @param expectedDestAmount Amount to be transferred to destAddress /// @param srcDecimals Decimals of source token /// @param destDecimals Decimals of destination token function doReserveTrades( IERC20Ext src, IERC20Ext dest, address payable destAddress, ReservesData memory reservesData, uint256 expectedDestAmount, uint256 srcDecimals, uint256 destDecimals ) internal virtual { if (src == dest) { // eth -> eth, need not do anything except for token -> eth: transfer eth to destAddress if (destAddress != (address(this))) { (bool success, ) = destAddress.call{value: expectedDestAmount}(""); require(success, "send dest qty failed"); } return; } tradeAndVerifyNetworkBalance( reservesData, src, dest, srcDecimals, destDecimals ); if (destAddress != address(this)) { // for eth -> token / token -> token, transfer tokens to destAddress dest.safeTransfer(destAddress, expectedDestAmount); } } /// @dev call trade from reserves and verify balances /// @param reservesData reservesData to trade /// @param src Source token of trade /// @param dest Destination token of trade /// @param srcDecimals Decimals of source token /// @param destDecimals Decimals of destination token function tradeAndVerifyNetworkBalance( ReservesData memory reservesData, IERC20Ext src, IERC20Ext dest, uint256 srcDecimals, uint256 destDecimals ) internal { // only need to verify src balance if src is not eth uint256 srcBalanceBefore = (src == ETH_TOKEN_ADDRESS) ? 0 : getBalance(src, address(this)); uint256 destBalanceBefore = getBalance(dest, address(this)); for(uint256 i = 0; i < reservesData.addresses.length; i++) { uint256 callValue = (src == ETH_TOKEN_ADDRESS) ? reservesData.srcAmounts[i] : 0; require( reservesData.addresses[i].trade{value: callValue}( src, reservesData.srcAmounts[i], dest, address(this), reservesData.rates[i], true ), "reserve trade failed" ); uint256 balanceAfter; if (src != ETH_TOKEN_ADDRESS) { // verify src balance only if it is not eth balanceAfter = getBalance(src, address(this)); // verify correct src amount is taken if (srcBalanceBefore >= balanceAfter && srcBalanceBefore - balanceAfter > reservesData.srcAmounts[i]) { revert("reserve takes high amount"); } srcBalanceBefore = balanceAfter; } // verify correct dest amount is received uint256 expectedDestAmount = calcDstQty( reservesData.srcAmounts[i], srcDecimals, destDecimals, reservesData.rates[i] ); balanceAfter = getBalance(dest, address(this)); if (balanceAfter < destBalanceBefore || balanceAfter - destBalanceBefore < expectedDestAmount) { revert("reserve returns low amount"); } destBalanceBefore = balanceAfter; } } /// @notice Use token address ETH_TOKEN_ADDRESS for ether /// @dev Trade API for kyberNetwork /// @param tradeData Main trade data object for trade info to be stored function trade(TradeData memory tradeData, bytes memory hint) internal virtual nonReentrant returns (uint256 destAmount) { tradeData.networkFeeBps = getAndUpdateNetworkFee(); validateTradeInput(tradeData.input); uint256 rateWithNetworkFee; (destAmount, rateWithNetworkFee) = calcRatesAndAmounts(tradeData, hint); require(rateWithNetworkFee > 0, "trade invalid, if hint involved, try parseHint API"); require(rateWithNetworkFee < MAX_RATE, "rate > MAX_RATE"); require(rateWithNetworkFee >= tradeData.input.minConversionRate, "rate < min rate"); uint256 actualSrcAmount; if (destAmount > tradeData.input.maxDestAmount) { // notice tradeData passed by reference and updated destAmount = tradeData.input.maxDestAmount; actualSrcAmount = calcTradeSrcAmountFromDest(tradeData); } else { actualSrcAmount = tradeData.input.srcAmount; } // token -> eth doReserveTrades( tradeData.input.src, ETH_TOKEN_ADDRESS, address(this), tradeData.tokenToEth, tradeData.tradeWei, tradeData.tokenToEth.decimals, ETH_DECIMALS ); // eth -> token doReserveTrades( ETH_TOKEN_ADDRESS, tradeData.input.dest, tradeData.input.destAddress, tradeData.ethToToken, destAmount, ETH_DECIMALS, tradeData.ethToToken.decimals ); handleChange( tradeData.input.src, tradeData.input.srcAmount, actualSrcAmount, tradeData.input.trader ); handleFees(tradeData); emit KyberTrade({ src: tradeData.input.src, dest: tradeData.input.dest, ethWeiValue: tradeData.tradeWei, networkFeeWei: tradeData.networkFeeWei, customPlatformFeeWei: tradeData.platformFeeWei, t2eIds: tradeData.tokenToEth.ids, e2tIds: tradeData.ethToToken.ids, t2eSrcAmounts: tradeData.tokenToEth.srcAmounts, e2tSrcAmounts: tradeData.ethToToken.srcAmounts, t2eRates: tradeData.tokenToEth.rates, e2tRates: tradeData.ethToToken.rates }); if (gasHelper != IGasHelper(0)) { (bool success, ) = address(gasHelper).call( abi.encodeWithSignature( "freeGas(address,address,address,uint256,bytes32[],bytes32[])", tradeData.input.platformWallet, tradeData.input.src, tradeData.input.dest, tradeData.tradeWei, tradeData.tokenToEth.ids, tradeData.ethToToken.ids ) ); // remove compilation warning success; } return (destAmount); } /// @notice If user maxDestAmount < actual dest amount, actualSrcAmount will be < srcAmount /// Calculate the change, and send it back to the user function handleChange( IERC20Ext src, uint256 srcAmount, uint256 requiredSrcAmount, address payable trader ) internal { if (requiredSrcAmount < srcAmount) { // if there is "change" send back to trader if (src == ETH_TOKEN_ADDRESS) { (bool success, ) = trader.call{value: (srcAmount - requiredSrcAmount)}(""); require(success, "Send change failed"); } else { src.safeTransfer(trader, (srcAmount - requiredSrcAmount)); } } } function initTradeInput( address payable trader, IERC20Ext src, IERC20Ext dest, uint256 srcAmount, address payable destAddress, uint256 maxDestAmount, uint256 minConversionRate, address payable platformWallet, uint256 platformFeeBps ) internal view returns (TradeData memory tradeData) { tradeData.input.trader = trader; tradeData.input.src = src; tradeData.input.srcAmount = srcAmount; tradeData.input.dest = dest; tradeData.input.destAddress = destAddress; tradeData.input.maxDestAmount = maxDestAmount; tradeData.input.minConversionRate = minConversionRate; tradeData.input.platformWallet = platformWallet; tradeData.input.platformFeeBps = platformFeeBps; tradeData.tokenToEth.decimals = getDecimals(src); tradeData.ethToToken.decimals = getDecimals(dest); } /// @notice This function does all calculations to find trade dest amount without accounting /// for maxDestAmount. Part of this process includes: /// - Call kyberMatchingEngine to parse hint and get an optional reserve list to trade. /// - Query reserve rates and call kyberMatchingEngine to use best reserve. /// - Calculate trade values and fee values. /// This function should set all TradeData information so that it can be later used without /// any ambiguity /// @param tradeData Main trade data object for trade info to be stored /// @param hint Advanced user instructions for the trade function calcRatesAndAmounts(TradeData memory tradeData, bytes memory hint) internal view returns (uint256 destAmount, uint256 rateWithNetworkFee) { validateFeeInput(tradeData.input, tradeData.networkFeeBps); // token -> eth: find best reserves match and calculate wei amount tradeData.tradeWei = calcDestQtyAndMatchReserves( tradeData.input.src, ETH_TOKEN_ADDRESS, tradeData.input.srcAmount, tradeData, tradeData.tokenToEth, hint ); require(tradeData.tradeWei <= MAX_QTY, "Trade wei > MAX_QTY"); if (tradeData.tradeWei == 0) { return (0, 0); } // calculate fees tradeData.platformFeeWei = (tradeData.tradeWei * tradeData.input.platformFeeBps) / BPS; tradeData.networkFeeWei = (((tradeData.tradeWei * tradeData.networkFeeBps) / BPS) * tradeData.feeAccountedBps) / BPS; assert(tradeData.tradeWei >= (tradeData.networkFeeWei + tradeData.platformFeeWei)); // eth -> token: find best reserves match and calculate trade dest amount uint256 actualSrcWei = tradeData.tradeWei - tradeData.networkFeeWei - tradeData.platformFeeWei; destAmount = calcDestQtyAndMatchReserves( ETH_TOKEN_ADDRESS, tradeData.input.dest, actualSrcWei, tradeData, tradeData.ethToToken, hint ); tradeData.networkFeeWei = (((tradeData.tradeWei * tradeData.networkFeeBps) / BPS) * tradeData.feeAccountedBps) / BPS; rateWithNetworkFee = calcRateFromQty( tradeData.input.srcAmount * (BPS - tradeData.input.platformFeeBps) / BPS, destAmount, tradeData.tokenToEth.decimals, tradeData.ethToToken.decimals ); } /// @notice Get trading reserves, source amounts, and calculate dest qty /// Store information into tradeData function calcDestQtyAndMatchReserves( IERC20Ext src, IERC20Ext dest, uint256 srcAmount, TradeData memory tradeData, ReservesData memory reservesData, bytes memory hint ) internal view returns (uint256 destAmount) { if (src == dest) { return srcAmount; } IKyberMatchingEngine.ProcessWithRate processWithRate; // get reserve list from kyberMatchingEngine (reservesData.ids, reservesData.splitsBps, processWithRate) = kyberMatchingEngine.getTradingReserves( src, dest, (tradeData.input.src != ETH_TOKEN_ADDRESS) && (tradeData.input.dest != ETH_TOKEN_ADDRESS), hint ); bool areAllReservesListed; (areAllReservesListed, reservesData.isFeeAccountedFlags, reservesData.isEntitledRebateFlags, reservesData.addresses) = kyberStorage.getReservesData(reservesData.ids, src, dest); if(!areAllReservesListed) { return 0; } require(reservesData.ids.length == reservesData.splitsBps.length, "bad split array"); require(reservesData.ids.length == reservesData.isFeeAccountedFlags.length, "bad fee array"); require(reservesData.ids.length == reservesData.isEntitledRebateFlags.length, "bad rebate array"); require(reservesData.ids.length == reservesData.addresses.length, "bad addresses array"); // calculate src trade amount per reserve and query rates // set data in reservesData struct uint256[] memory feesAccountedDestBps = calcSrcAmountsAndGetRates( reservesData, src, dest, srcAmount, tradeData ); // if matching engine requires processing with rate data. call doMatch and update reserve list if (processWithRate == IKyberMatchingEngine.ProcessWithRate.Required) { uint256[] memory selectedIndexes = kyberMatchingEngine.doMatch( src, dest, reservesData.srcAmounts, feesAccountedDestBps, reservesData.rates ); updateReservesList(reservesData, selectedIndexes); } // calculate dest amount and fee paying data of this part (t2e or e2t) destAmount = validateTradeCalcDestQtyAndFeeData(src, reservesData, tradeData); } /// @notice Calculates source amounts per reserve. Does get rate call function calcSrcAmountsAndGetRates( ReservesData memory reservesData, IERC20Ext src, IERC20Ext dest, uint256 srcAmount, TradeData memory tradeData ) internal view returns (uint256[] memory feesAccountedDestBps) { uint256 numReserves = reservesData.ids.length; uint256 srcAmountAfterFee; uint256 destAmountFeeBps; if (src == ETH_TOKEN_ADDRESS) { // @notice srcAmount is after deducting fees from tradeWei // @notice using tradeWei to calculate fee so eth -> token symmetric to token -> eth srcAmountAfterFee = srcAmount - (tradeData.tradeWei * tradeData.networkFeeBps / BPS); } else { srcAmountAfterFee = srcAmount; destAmountFeeBps = tradeData.networkFeeBps; } reservesData.srcAmounts = new uint256[](numReserves); reservesData.rates = new uint256[](numReserves); feesAccountedDestBps = new uint256[](numReserves); // iterate reserve list. validate data. calculate srcAmount according to splits and fee data. for (uint256 i = 0; i < numReserves; i++) { require( reservesData.splitsBps[i] > 0 && reservesData.splitsBps[i] <= BPS, "invalid split bps" ); if (reservesData.isFeeAccountedFlags[i]) { reservesData.srcAmounts[i] = srcAmountAfterFee * reservesData.splitsBps[i] / BPS; feesAccountedDestBps[i] = destAmountFeeBps; } else { reservesData.srcAmounts[i] = (srcAmount * reservesData.splitsBps[i]) / BPS; } // get rate with calculated src amount reservesData.rates[i] = reservesData.addresses[i].getConversionRate( src, dest, reservesData.srcAmounts[i], block.number ); } } function calculateRebates(TradeData memory tradeData) internal view returns (address[] memory rebateWallets, uint256[] memory rebatePercentBps) { rebateWallets = new address[](tradeData.numEntitledRebateReserves); rebatePercentBps = new uint256[](tradeData.numEntitledRebateReserves); if (tradeData.numEntitledRebateReserves == 0) { return (rebateWallets, rebatePercentBps); } uint256 index; bytes32[] memory rebateReserveIds = new bytes32[](tradeData.numEntitledRebateReserves); // token -> eth index = createRebateEntitledList( rebateReserveIds, rebatePercentBps, tradeData.tokenToEth, index, tradeData.feeAccountedBps ); // eth -> token createRebateEntitledList( rebateReserveIds, rebatePercentBps, tradeData.ethToToken, index, tradeData.feeAccountedBps ); rebateWallets = kyberStorage.getRebateWalletsFromIds(rebateReserveIds); } function createRebateEntitledList( bytes32[] memory rebateReserveIds, uint256[] memory rebatePercentBps, ReservesData memory reservesData, uint256 index, uint256 feeAccountedBps ) internal pure returns (uint256) { uint256 _index = index; for (uint256 i = 0; i < reservesData.isEntitledRebateFlags.length; i++) { if (reservesData.isEntitledRebateFlags[i]) { rebateReserveIds[_index] = reservesData.ids[i]; rebatePercentBps[_index] = (reservesData.splitsBps[i] * BPS) / feeAccountedBps; _index++; } } return _index; } /// @dev Checks a trade input validity, including correct src amounts /// @param input Trade input structure function validateTradeInput(TradeInput memory input) internal view { require(isEnabled, "network disabled"); require(kyberProxyContracts[msg.sender], "bad sender"); require(tx.gasprice <= maxGasPriceValue, "gas price"); require(input.srcAmount <= MAX_QTY, "srcAmt > MAX_QTY"); require(input.srcAmount != 0, "0 srcAmt"); require(input.destAddress != address(0), "dest add 0"); require(input.src != input.dest, "src = dest"); if (input.src == ETH_TOKEN_ADDRESS) { require(msg.value == input.srcAmount); // kyberProxy issues message here } else { require(msg.value == 0); // kyberProxy issues message here // funds should have been moved to this contract already. require(input.src.balanceOf(address(this)) >= input.srcAmount, "no tokens"); } } /// @notice Gets the network fee from kyberDao (or use default). View function for getExpectedRate function getNetworkFee() internal view returns (uint256 networkFeeBps) { uint256 expiryTimestamp; (networkFeeBps, expiryTimestamp) = readNetworkFeeData(); if (expiryTimestamp < now && kyberDao != IKyberDao(0)) { (networkFeeBps, expiryTimestamp) = kyberDao.getLatestNetworkFeeData(); } } function readNetworkFeeData() internal view returns (uint256 feeBps, uint256 expiryTimestamp) { feeBps = uint256(networkFeeData.feeBps); expiryTimestamp = uint256(networkFeeData.expiryTimestamp); } /// @dev Checks fee input validity, including correct src amounts /// @param input Trade input structure /// @param networkFeeBps Network fee in bps. function validateFeeInput(TradeInput memory input, uint256 networkFeeBps) internal pure { require(input.platformFeeBps < BPS, "platformFee high"); require(input.platformFeeBps + networkFeeBps + networkFeeBps < BPS, "fees high"); } /// @notice Update reserve data with selected reserves from kyberMatchingEngine function updateReservesList(ReservesData memory reservesData, uint256[] memory selectedIndexes) internal pure { uint256 numReserves = selectedIndexes.length; require(numReserves <= reservesData.addresses.length, "doMatch: too many reserves"); IKyberReserve[] memory reserveAddresses = new IKyberReserve[](numReserves); bytes32[] memory reserveIds = new bytes32[](numReserves); uint256[] memory splitsBps = new uint256[](numReserves); bool[] memory isFeeAccountedFlags = new bool[](numReserves); bool[] memory isEntitledRebateFlags = new bool[](numReserves); uint256[] memory srcAmounts = new uint256[](numReserves); uint256[] memory rates = new uint256[](numReserves); // update participating resevres and all data (rates, srcAmounts, feeAcounted etc.) for (uint256 i = 0; i < numReserves; i++) { reserveAddresses[i] = reservesData.addresses[selectedIndexes[i]]; reserveIds[i] = reservesData.ids[selectedIndexes[i]]; splitsBps[i] = reservesData.splitsBps[selectedIndexes[i]]; isFeeAccountedFlags[i] = reservesData.isFeeAccountedFlags[selectedIndexes[i]]; isEntitledRebateFlags[i] = reservesData.isEntitledRebateFlags[selectedIndexes[i]]; srcAmounts[i] = reservesData.srcAmounts[selectedIndexes[i]]; rates[i] = reservesData.rates[selectedIndexes[i]]; } // update values reservesData.addresses = reserveAddresses; reservesData.ids = reserveIds; reservesData.splitsBps = splitsBps; reservesData.isFeeAccountedFlags = isFeeAccountedFlags; reservesData.isEntitledRebateFlags = isEntitledRebateFlags; reservesData.rates = rates; reservesData.srcAmounts = srcAmounts; } /// @notice Verify split values bps and reserve ids, /// then calculate the destQty from srcAmounts and rates /// @dev Each split bps must be in range (0, BPS] /// @dev Total split bps must be 100% /// @dev Reserve ids must be increasing function validateTradeCalcDestQtyAndFeeData( IERC20Ext src, ReservesData memory reservesData, TradeData memory tradeData ) internal pure returns (uint256 totalDestAmount) { uint256 totalBps; uint256 srcDecimals = (src == ETH_TOKEN_ADDRESS) ? ETH_DECIMALS : reservesData.decimals; uint256 destDecimals = (src == ETH_TOKEN_ADDRESS) ? reservesData.decimals : ETH_DECIMALS; for (uint256 i = 0; i < reservesData.addresses.length; i++) { if (i > 0 && (uint256(reservesData.ids[i]) <= uint256(reservesData.ids[i - 1]))) { return 0; // ids are not in increasing order } totalBps += reservesData.splitsBps[i]; uint256 destAmount = calcDstQty( reservesData.srcAmounts[i], srcDecimals, destDecimals, reservesData.rates[i] ); if (destAmount == 0) { return 0; } totalDestAmount += destAmount; if (reservesData.isFeeAccountedFlags[i]) { tradeData.feeAccountedBps += reservesData.splitsBps[i]; if (reservesData.isEntitledRebateFlags[i]) { tradeData.numEntitledRebateReserves++; } } } if (totalBps != BPS) { return 0; } } /// @notice Recalculates tradeWei, network and platform fees, and actual source amount needed for the trade /// in the event actualDestAmount > maxDestAmount function calcTradeSrcAmountFromDest(TradeData memory tradeData) internal pure virtual returns (uint256 actualSrcAmount) { uint256 weiAfterDeductingFees; if (tradeData.input.dest != ETH_TOKEN_ADDRESS) { weiAfterDeductingFees = calcTradeSrcAmount( tradeData.tradeWei - tradeData.platformFeeWei - tradeData.networkFeeWei, ETH_DECIMALS, tradeData.ethToToken.decimals, tradeData.input.maxDestAmount, tradeData.ethToToken ); } else { weiAfterDeductingFees = tradeData.input.maxDestAmount; } // reverse calculation, because we are working backwards uint256 newTradeWei = (weiAfterDeductingFees * BPS * BPS) / ((BPS * BPS) - (tradeData.networkFeeBps * tradeData.feeAccountedBps + tradeData.input.platformFeeBps * BPS)); tradeData.tradeWei = minOf(newTradeWei, tradeData.tradeWei); // recalculate network and platform fees based on tradeWei tradeData.networkFeeWei = (((tradeData.tradeWei * tradeData.networkFeeBps) / BPS) * tradeData.feeAccountedBps) / BPS; tradeData.platformFeeWei = (tradeData.tradeWei * tradeData.input.platformFeeBps) / BPS; if (tradeData.input.src != ETH_TOKEN_ADDRESS) { actualSrcAmount = calcTradeSrcAmount( tradeData.input.srcAmount, tradeData.tokenToEth.decimals, ETH_DECIMALS, tradeData.tradeWei, tradeData.tokenToEth ); } else { actualSrcAmount = tradeData.tradeWei; } assert(actualSrcAmount <= tradeData.input.srcAmount); } /// @notice Recalculates srcAmounts and stores into tradingReserves, given the new destAmount. /// Uses the original proportion of srcAmounts and rates to determine new split destAmounts, /// then calculate the respective srcAmounts /// @dev Due to small rounding errors, will fallback to current src amounts if new src amount is greater function calcTradeSrcAmount( uint256 srcAmount, uint256 srcDecimals, uint256 destDecimals, uint256 destAmount, ReservesData memory reservesData ) internal pure returns (uint256 newSrcAmount) { uint256 totalWeightedDestAmount; for (uint256 i = 0; i < reservesData.srcAmounts.length; i++) { totalWeightedDestAmount += reservesData.srcAmounts[i] * reservesData.rates[i]; } uint256[] memory newSrcAmounts = new uint256[](reservesData.srcAmounts.length); uint256 destAmountSoFar; uint256 currentSrcAmount; uint256 destAmountSplit; for (uint256 i = 0; i < reservesData.srcAmounts.length; i++) { currentSrcAmount = reservesData.srcAmounts[i]; require(destAmount * currentSrcAmount * reservesData.rates[i] / destAmount == currentSrcAmount * reservesData.rates[i], "multiplication overflow"); destAmountSplit = i == (reservesData.srcAmounts.length - 1) ? (destAmount - destAmountSoFar) : (destAmount * currentSrcAmount * reservesData.rates[i]) / totalWeightedDestAmount; destAmountSoFar += destAmountSplit; newSrcAmounts[i] = calcSrcQty( destAmountSplit, srcDecimals, destDecimals, reservesData.rates[i] ); if (newSrcAmounts[i] > currentSrcAmount) { // revert back to use current src amounts return srcAmount; } newSrcAmount += newSrcAmounts[i]; } // new src amounts are used only when all of them aren't greater then current srcAmounts reservesData.srcAmounts = newSrcAmounts; } }
till we read value from kyberDao
uint256 internal constant DEFAULT_NETWORK_FEE_BPS = 25;
5,532,739
[ 1, 88, 737, 732, 855, 460, 628, 417, 93, 744, 11412, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 2713, 5381, 3331, 67, 28047, 67, 8090, 41, 67, 38, 5857, 273, 6969, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x29d932Ccd887860f8f29c15fD7f09D5Bd82080e8/sources/util/ABDKMath64x64.sol
Minimum value signed 64.64-bit fixed point number may have./ Maximum value signed 64.64-bit fixed point number may have./* Convert signed 256-bit integer number into signed 64.64-bit fixed point number. Revert on overflow. @param x signed 256-bit integer number @return signed 64.64-bit fixed point number/
function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } }
717,060
[ 1, 13042, 460, 6726, 5178, 18, 1105, 17, 3682, 5499, 1634, 1300, 2026, 1240, 18, 19, 18848, 460, 6726, 5178, 18, 1105, 17, 3682, 5499, 1634, 1300, 2026, 1240, 18, 19, 4037, 6726, 8303, 17, 3682, 3571, 1300, 1368, 6726, 5178, 18, 1105, 17, 3682, 5499, 1634, 1300, 18, 225, 868, 1097, 603, 9391, 18, 225, 619, 6726, 8303, 17, 3682, 3571, 1300, 327, 6726, 5178, 18, 1105, 17, 3682, 5499, 1634, 1300, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 628, 1702, 261, 474, 5034, 619, 13, 2713, 16618, 1135, 261, 474, 10392, 13, 288, 203, 565, 22893, 288, 203, 3639, 2583, 261, 92, 1545, 300, 20, 92, 28, 12648, 17877, 597, 619, 1648, 374, 92, 27, 8998, 8998, 18343, 42, 1769, 203, 3639, 327, 509, 10392, 261, 92, 2296, 5178, 1769, 203, 565, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x73BCA358e83dE2e1e4B328a3F200aBFed32BE654/sources/contracts/v4/extensions/Whitelistable.sol
* Get WL config for given editionId, amout, and mintPrice. Should not be used internally when trying to modify the state as it returns a memory copy of the structs/ This reverts if edition does not exist
function getWLConfig( uint256 editionId, uint8 amount, uint24 mintPriceInFinney ) public view returns (WhitelistableState.WhitelistConfig memory) { WhitelistableState.WLState storage state = WhitelistableState ._getWhitelistableState(); getEdition(editionId); uint256 wlId = uint256( keccak256(abi.encodePacked(editionId, amount, mintPriceInFinney)) ); WhitelistableState.WhitelistConfig storage whitelistConfig = state ._whitelistConfig[wlId]; if (whitelistConfig.amount == 0) { revert CustomErrors.NotFound(); } return whitelistConfig; }
16,448,691
[ 1, 967, 678, 48, 642, 364, 864, 28432, 548, 16, 2125, 659, 16, 471, 312, 474, 5147, 18, 9363, 486, 506, 1399, 12963, 1347, 8374, 358, 5612, 326, 919, 487, 518, 1135, 279, 3778, 1610, 434, 326, 8179, 19, 1220, 15226, 87, 309, 28432, 1552, 486, 1005, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13876, 48, 809, 12, 203, 3639, 2254, 5034, 28432, 548, 16, 203, 3639, 2254, 28, 3844, 16, 203, 3639, 2254, 3247, 312, 474, 5147, 382, 6187, 82, 402, 203, 565, 262, 1071, 1476, 1135, 261, 18927, 429, 1119, 18, 18927, 809, 3778, 13, 288, 203, 3639, 3497, 7523, 429, 1119, 18, 59, 48, 1119, 2502, 919, 273, 3497, 7523, 429, 1119, 203, 5411, 263, 67, 588, 18927, 429, 1119, 5621, 203, 203, 3639, 4774, 1460, 12, 329, 608, 548, 1769, 203, 203, 3639, 2254, 5034, 19564, 548, 273, 2254, 5034, 12, 203, 5411, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 329, 608, 548, 16, 3844, 16, 312, 474, 5147, 382, 6187, 82, 402, 3719, 203, 3639, 11272, 203, 3639, 3497, 7523, 429, 1119, 18, 18927, 809, 2502, 10734, 809, 273, 919, 203, 5411, 263, 67, 20409, 809, 63, 21504, 548, 15533, 203, 203, 3639, 309, 261, 20409, 809, 18, 8949, 422, 374, 13, 288, 203, 5411, 15226, 6082, 4229, 18, 2768, 5621, 203, 3639, 289, 203, 203, 3639, 327, 10734, 809, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x6a61250ecAcaFcdF8f9F7A305AFBA7b8dEEC0DbA/sources/contracts/smart-contract-wallet/WalletFactory.sol
event WalletCreated(address indexed _proxy, address indexed _implementation, address indexed _owner); EOA + Version tracking
event WalletCreated(address indexed _proxy, address indexed _implementation, address indexed _owner, string version, uint256 _index);
5,670,548
[ 1, 2575, 20126, 6119, 12, 2867, 8808, 389, 5656, 16, 1758, 8808, 389, 30810, 16, 1758, 8808, 389, 8443, 1769, 512, 28202, 397, 4049, 11093, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 20126, 6119, 12, 2867, 8808, 389, 5656, 16, 1758, 8808, 389, 30810, 16, 1758, 8808, 389, 8443, 16, 533, 1177, 16, 2254, 5034, 389, 1615, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title SetherToken * @dev Sether ERC20 Token that can be minted. * It is meant to be used in sether crowdsale contract. */ contract SetherToken is MintableToken { string public constant name = "Sether"; string public constant symbol = "SETH"; uint8 public constant decimals = 18; function getTotalSupply() public returns (uint256) { return totalSupply; } } /** * @title SetherBaseCrowdsale * @dev SetherBaseCrowdsale is a base contract for managing a sether token crowdsale. */ contract SetherBaseCrowdsale { using SafeMath for uint256; // The token being sold SetherToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many finney per token uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event SethTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function SetherBaseCrowdsale(uint256 _rate, address _wallet) { require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); rate = _rate; wallet = _wallet; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = computeTokens(weiAmount); require(isWithinTokenAllocLimit(tokens)); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); SethTokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } // @return true if crowdsale event has started function hasStarted() public constant returns (bool) { return now < startTime; } // send ether to the fund collection wallet function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } //Override this method with token distribution strategy function computeTokens(uint256 weiAmount) internal returns (uint256) { //To be overriden } //Override this method with token limitation strategy function isWithinTokenAllocLimit(uint256 _tokens) internal returns (bool) { //To be overriden } // creates the token to be sold. function createTokenContract() internal returns (SetherToken) { return new SetherToken(); } } /** * @title SetherMultiStepCrowdsale * @dev Multi-step payment policy contract that extends SetherBaseCrowdsale */ contract SetherMultiStepCrowdsale is SetherBaseCrowdsale { uint256 public constant PRESALE_LIMIT = 25 * (10 ** 6) * (10 ** 18); uint256 public constant CROWDSALE_LIMIT = 55 * (10 ** 6) * (10 ** 18); uint256 public constant PRESALE_BONUS_LIMIT = 1 * (10 ** 17); // Presale period (includes holidays) uint public constant PRESALE_PERIOD = 53 days; // Crowdsale first week period (constants for proper testing) uint public constant CROWD_WEEK1_PERIOD = 7 days; // Crowdsale second week period uint public constant CROWD_WEEK2_PERIOD = 7 days; //Crowdsale third week period uint public constant CROWD_WEEK3_PERIOD = 7 days; //Crowdsale last week period uint public constant CROWD_WEEK4_PERIOD = 7 days; uint public constant PRESALE_BONUS = 40; uint public constant CROWD_WEEK1_BONUS = 25; uint public constant CROWD_WEEK2_BONUS = 20; uint public constant CROWD_WEEK3_BONUS = 10; uint256 public limitDatePresale; uint256 public limitDateCrowdWeek1; uint256 public limitDateCrowdWeek2; uint256 public limitDateCrowdWeek3; function SetherMultiStepCrowdsale() { } function isWithinPresaleTimeLimit() internal returns (bool) { return now <= limitDatePresale; } function isWithinCrowdWeek1TimeLimit() internal returns (bool) { return now <= limitDateCrowdWeek1; } function isWithinCrowdWeek2TimeLimit() internal returns (bool) { return now <= limitDateCrowdWeek2; } function isWithinCrowdWeek3TimeLimit() internal returns (bool) { return now <= limitDateCrowdWeek3; } function isWithinCrodwsaleTimeLimit() internal returns (bool) { return now <= endTime && now > limitDatePresale; } function isWithinPresaleLimit(uint256 _tokens) internal returns (bool) { return token.getTotalSupply().add(_tokens) <= PRESALE_LIMIT; } function isWithinCrowdsaleLimit(uint256 _tokens) internal returns (bool) { return token.getTotalSupply().add(_tokens) <= CROWDSALE_LIMIT; } function validPurchase() internal constant returns (bool) { return super.validPurchase() && !(isWithinPresaleTimeLimit() && msg.value < PRESALE_BONUS_LIMIT); } function isWithinTokenAllocLimit(uint256 _tokens) internal returns (bool) { return (isWithinPresaleTimeLimit() && isWithinPresaleLimit(_tokens)) || (isWithinCrodwsaleTimeLimit() && isWithinCrowdsaleLimit(_tokens)); } function computeTokens(uint256 weiAmount) internal returns (uint256) { uint256 appliedBonus = 0; if (isWithinPresaleTimeLimit()) { appliedBonus = PRESALE_BONUS; } else if (isWithinCrowdWeek1TimeLimit()) { appliedBonus = CROWD_WEEK1_BONUS; } else if (isWithinCrowdWeek2TimeLimit()) { appliedBonus = CROWD_WEEK2_BONUS; } else if (isWithinCrowdWeek3TimeLimit()) { appliedBonus = CROWD_WEEK3_BONUS; } return weiAmount.mul(10).mul(100 + appliedBonus).div(rate); } } /** * @title SetherCappedCrowdsale * @dev Extension of SetherBaseCrowdsale with a max amount of funds raised */ contract SetherCappedCrowdsale is SetherMultiStepCrowdsale { using SafeMath for uint256; uint256 public constant HARD_CAP = 55 * (10 ** 6) * (10 ** 18); function SetherCappedCrowdsale() { } // overriding SetherBaseCrowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal constant returns (bool) { bool withinCap = weiRaised.add(msg.value) <= HARD_CAP; return super.validPurchase() && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= HARD_CAP; return super.hasEnded() || capReached; } } /** * @title SetherStartableCrowdsale * @dev Extension of SetherBaseCrowdsale where an owner can start the crowdsale */ contract SetherStartableCrowdsale is SetherBaseCrowdsale, Ownable { using SafeMath for uint256; bool public isStarted = false; event SetherStarted(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function start() onlyOwner public { require(!isStarted); require(!hasStarted()); starting(); SetherStarted(); isStarted = true; } /** * @dev Can be overridden to add start logic. The overriding function * should call super.starting() to ensure the chain of starting is * executed entirely. */ function starting() internal { //To be overriden } } /** * @title SetherFinalizableCrowdsale * @dev Extension of SetherBaseCrowdsale where an owner can do extra work * after finishing. */ contract SetherFinalizableCrowdsale is SetherBaseCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event SetherFinalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); SetherFinalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { //To be overriden } } /** * @title SetherCrowdsale * @dev This is Sether's crowdsale contract. */ contract SetherCrowdsale is SetherCappedCrowdsale, SetherStartableCrowdsale, SetherFinalizableCrowdsale { function SetherCrowdsale(uint256 rate, address _wallet) SetherCappedCrowdsale() SetherFinalizableCrowdsale() SetherStartableCrowdsale() SetherMultiStepCrowdsale() SetherBaseCrowdsale(rate, _wallet) { } function starting() internal { super.starting(); startTime = now; limitDatePresale = startTime + PRESALE_PERIOD; limitDateCrowdWeek1 = limitDatePresale + CROWD_WEEK1_PERIOD; limitDateCrowdWeek2 = limitDateCrowdWeek1 + CROWD_WEEK2_PERIOD; limitDateCrowdWeek3 = limitDateCrowdWeek2 + CROWD_WEEK3_PERIOD; endTime = limitDateCrowdWeek3 + CROWD_WEEK4_PERIOD; } function finalization() internal { super.finalization(); uint256 ownerShareTokens = token.getTotalSupply().mul(9).div(11); token.mint(wallet, ownerShareTokens); } }
creates the token to be sold.
function createTokenContract() internal returns (SetherToken) { return new SetherToken(); }
1,013,922
[ 1, 19787, 326, 1147, 358, 506, 272, 1673, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 1345, 8924, 1435, 2713, 1135, 261, 55, 2437, 1345, 13, 288, 203, 3639, 327, 394, 348, 2437, 1345, 5621, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x929C3811906F006AD50Dbd5a104b1C17eEA85767/sources/contracts/TropyverseLand.sol
* the Metadata extension, but not including the Enumerable extension, which is available separately as {ERC721Enumerable}./ Token name Token symbol Mapping from token ID to owner address Mapping owner address to token count Mapping from token ID to approved address Mapping from owner to operator approvals
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; mapping(uint256 => address) private _owners; mapping(address => uint256) private _balances; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: address zero is not a valid owner" ); return _balances[owner]; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: invalid token ID"); return owner; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { _requireMinted(tokenId); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not token owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { _requireMinted(tokenId); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner nor approved" ); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner nor approved" ); _safeTransfer(from, to, tokenId, data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { address owner = ERC721.ownerOf(tokenId); return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } 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); } function _requireMinted(uint256 tokenId) internal view virtual { require(_exists(tokenId), "ERC721: invalid token ID"); } 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; if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } 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; if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } 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; if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } catch (bytes memory reason) { 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; if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } else { 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; if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } else { ) internal virtual {} ) internal virtual {} }
3,063,308
[ 1, 5787, 6912, 2710, 16, 1496, 486, 6508, 326, 6057, 25121, 2710, 16, 1492, 353, 2319, 18190, 487, 288, 654, 39, 27, 5340, 3572, 25121, 5496, 19, 3155, 508, 3155, 3273, 9408, 628, 1147, 1599, 358, 3410, 1758, 9408, 3410, 1758, 358, 1147, 1056, 9408, 628, 1147, 1599, 358, 20412, 1758, 9408, 628, 3410, 358, 3726, 6617, 4524, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 27, 5340, 353, 1772, 16, 4232, 39, 28275, 16, 467, 654, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 2277, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 995, 414, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 12053, 4524, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 3238, 389, 9497, 12053, 4524, 31, 203, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 565, 289, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 12, 654, 39, 28275, 16, 467, 654, 39, 28275, 13, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 203, 5411, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 2934, 5831, 548, 747, 203, 5411, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 2277, 2934, 5831, 548, 747, 203, 5411, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 2 ]
./partial_match/5/0x9e0861844F40B48207e6c5D384D53Dfe27f4a8EC/sources/DeporRPOSValidatorData.sol
profitRate/10000
uint256 profitRate;
16,833,309
[ 1, 685, 7216, 4727, 19, 23899, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 450, 7216, 4727, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xBCE54D5fFFC38a2d33496dFa9A4c37A93bC592A4/sources/CORD.sol
* @dev Transfer token for a specified addresses @param from The address to transfer from. @param to The address to transfer to. @param value The amount to be transferred./
function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _whenSent[from]=block.timestamp; if(_taxRate>0) { uint256 totax=value.mul(_taxRate).div(10000); uint256 tosend=value.sub(totax); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(tosend); _balances[_taxBenefit] = _balances[_taxBenefit].add(totax); emit Transfer(from, to, tosend); emit Transfer(from, _taxBenefit, totax); } else { _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } }
8,654,633
[ 1, 5912, 1147, 364, 279, 1269, 6138, 225, 628, 1021, 1758, 358, 7412, 628, 18, 225, 358, 1021, 1758, 358, 7412, 358, 18, 225, 460, 1021, 3844, 358, 506, 906, 4193, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 2713, 288, 203, 565, 2583, 12, 1132, 1648, 389, 70, 26488, 63, 2080, 19226, 203, 565, 2583, 12, 869, 480, 1758, 12, 20, 10019, 203, 565, 389, 13723, 7828, 63, 2080, 65, 33, 2629, 18, 5508, 31, 203, 565, 309, 24899, 8066, 4727, 34, 20, 13, 288, 203, 377, 2254, 5034, 9997, 651, 33, 1132, 18, 16411, 24899, 8066, 4727, 2934, 2892, 12, 23899, 1769, 203, 377, 2254, 5034, 358, 4661, 33, 1132, 18, 1717, 12, 3307, 651, 1769, 203, 377, 389, 70, 26488, 63, 2080, 65, 273, 389, 70, 26488, 63, 2080, 8009, 1717, 12, 1132, 1769, 203, 377, 389, 70, 26488, 63, 869, 65, 273, 389, 70, 26488, 63, 869, 8009, 1289, 12, 14627, 409, 1769, 203, 377, 389, 70, 26488, 63, 67, 8066, 38, 4009, 7216, 65, 273, 389, 70, 26488, 63, 67, 8066, 38, 4009, 7216, 8009, 1289, 12, 3307, 651, 1769, 203, 377, 3626, 12279, 12, 2080, 16, 358, 16, 358, 4661, 1769, 203, 377, 3626, 12279, 12, 2080, 16, 389, 8066, 38, 4009, 7216, 16, 9997, 651, 1769, 203, 565, 289, 203, 565, 469, 288, 203, 377, 389, 70, 26488, 63, 2080, 65, 273, 389, 70, 26488, 63, 2080, 8009, 1717, 12, 1132, 1769, 203, 377, 389, 70, 26488, 63, 869, 65, 273, 389, 70, 26488, 63, 869, 8009, 1289, 12, 1132, 1769, 203, 377, 3626, 12279, 12, 2080, 16, 358, 16, 460, 1769, 203, 565, 289, 203, 225, 289, 203, 21281, 2, -100 ]
./full_match/1/0xe86C5ea96eA47D3A9D835672C1428329bD0bb7Af/sources/contracts/subdomain-registrar/TalSubdomainRegistrar.sol
* @dev Implements an ENS registrar that sells subdomains on behalf of their owners. Users may register a subdomain by calling `register` with the name of the domain they wish to register under, and the label hash of the subdomain they want to register. The registrar then configures a simple default resolver, which resolves `addr` lookups to the new owner, and sets the `owner` account as the owner of the subdomain in ENS. Critically, this contract does not check one key property of a listed domain: - Is the name UTS46 normalised? User applications MUST check these two elements for each domain before offering them to users for registration. Applications should additionally check that the domains they are offering to register are controlled by this registrar, since calls to `register` will fail if this is not the case./
contract TalSubdomainRegistrar is Ownable, ITalRegistrarInterface { bytes32 public immutable ROOT_NODE; ENS public ensRegistry; PublicResolver public publicResolver; DNSRegistrar public dnsRegistrar; AggregatorV3Interface internal priceFeed; uint256 public subdomainFee; bool public stopped = false; uint256 internal constant MUL = 1e18; constructor( ENS ens, PublicResolver resolver, DNSRegistrar registrar, AggregatorV3Interface priceFeedAddress, bytes32 node, address contractOwner, uint256 initialSubdomainFee import {PublicResolver} from "@ensdomains/ens-contracts/contracts/resolvers/PublicResolver.sol"; import {DNSRegistrar} from "@ensdomains/ens-contracts/contracts/dnsregistrar/DNSRegistrar.sol"; import {ENS} from "@ensdomains/ens-contracts/contracts/registry/ENS.sol"; import {DNSSEC} from "@ensdomains/ens-contracts/contracts/dnssec-oracle/DNSSEC.sol"; import {ITalRegistrarInterface} from "./ITalRegistrarInterface.sol"; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; ) { ensRegistry = ens; publicResolver = resolver; dnsRegistrar = registrar; ROOT_NODE = node; subdomainFee = initialSubdomainFee; priceFeed = priceFeedAddress; transferOwnership(contractOwner); } modifier notStopped() { require(!stopped, "TALSUBDOMAIN_REGISTRAR: Contract is currently stopped."); _; } function transferDomainOwnership(address newDomainOwner) public override onlyOwner { ensRegistry.setOwner(ROOT_NODE, newDomainOwner); emit DomainOwnershipTransferred(newDomainOwner); } function subDomainOwner(string memory subdomainLabel) public view override returns (address subDomainOwnerAddress) { bytes32 labelHash = keccak256(bytes(subdomainLabel)); return ensRegistry.owner(keccak256(abi.encodePacked(ROOT_NODE, labelHash))); } function register(string memory subdomainLabel) public payable override notStopped { bytes32 labelHash = keccak256(bytes(subdomainLabel)); bytes32 childNode = keccak256(abi.encodePacked(ROOT_NODE, labelHash)); address subdomainOwner = ensRegistry.owner(childNode); require(subdomainOwner == address(0x0), "TALSUBDOMAIN_REGISTRAR: SUBDOMAIN_ALREADY_REGISTERED"); _payAndRegister(_msgSender(), subdomainLabel, labelHash, childNode); } function freeRegister(string memory subdomainLabel, address subdomainNewOwner) public override onlyOwner { bytes32 labelHash = keccak256(bytes(subdomainLabel)); bytes32 childNode = keccak256(abi.encodePacked(ROOT_NODE, labelHash)); address subdomainOwner = ensRegistry.owner(childNode); require(subdomainOwner == address(0x0), "TALSUBDOMAIN_REGISTRAR: SUBDOMAIN_ALREADY_REGISTERED"); _register(subdomainNewOwner, subdomainLabel, labelHash, childNode, 0); } function revokeSubdomain(string memory subdomainLabel) public override onlyOwner { _revoke(subdomainLabel); } function setPublicResolver(PublicResolver resolver) public override onlyOwner { publicResolver = resolver; } function setSubdomainFee(uint256 newSubdomainFee) public override onlyOwner { require(newSubdomainFee != subdomainFee, "TALSUBDOMAIN_REGISTRAR: New fee matches the current fee"); subdomainFee = newSubdomainFee; emit SubDomainFeeChanged(subdomainFee); } function stop() public override notStopped onlyOwner { stopped = true; } function open() public override onlyOwner { stopped = false; } function configureDnsOwnership( bytes memory name, DNSSEC.RRSetWithSignature[] memory input, bytes memory proof ) public override onlyOwner { dnsRegistrar.proveAndClaimWithResolver(name, input, proof, address(publicResolver), address(this)); } function domainPriceInEth() public view override returns (uint256 price) { if (subdomainFee == 0) { return 0; } (, int256 ethUsdPrice, , , ) = priceFeed.latestRoundData(); return SafeMath.div(SafeMath.mul(subdomainFeeWithMUL, MUL), uint256(adjustedPrice)); } function domainPriceInEth() public view override returns (uint256 price) { if (subdomainFee == 0) { return 0; } (, int256 ethUsdPrice, , , ) = priceFeed.latestRoundData(); return SafeMath.div(SafeMath.mul(subdomainFeeWithMUL, MUL), uint256(adjustedPrice)); } uint256 subdomainFeeWithMUL = SafeMath.mul(subdomainFee, MUL); function _payAndRegister( address account, string memory subdomainLabel, bytes32 labelHash, bytes32 childNode ) internal { uint256 ethSubdomainFee = domainPriceInEth(); require(msg.value >= ethSubdomainFee, "TALSUBDOMAIN_REGISTRAR: Amount passed is not enough"); if (msg.value > ethSubdomainFee) { payable(_msgSender()).transfer(msg.value - ethSubdomainFee); } payable(owner()).transfer(ethSubdomainFee); _register(account, subdomainLabel, labelHash, childNode, ethSubdomainFee); } function _payAndRegister( address account, string memory subdomainLabel, bytes32 labelHash, bytes32 childNode ) internal { uint256 ethSubdomainFee = domainPriceInEth(); require(msg.value >= ethSubdomainFee, "TALSUBDOMAIN_REGISTRAR: Amount passed is not enough"); if (msg.value > ethSubdomainFee) { payable(_msgSender()).transfer(msg.value - ethSubdomainFee); } payable(owner()).transfer(ethSubdomainFee); _register(account, subdomainLabel, labelHash, childNode, ethSubdomainFee); } function _register( address account, string memory subdomainLabel, bytes32 labelHash, bytes32 childNode, uint256 fee ) internal { ensRegistry.setSubnodeRecord(ROOT_NODE, labelHash, address(this), address(publicResolver), 0); publicResolver.setAddr(childNode, account); ensRegistry.setSubnodeOwner(ROOT_NODE, labelHash, account); emit SubDomainRegistered(subdomainLabel, fee, account); } function _revoke(string memory subdomainLabel) internal { bytes32 labelHash = keccak256(bytes(subdomainLabel)); bytes32 childNode = keccak256(abi.encodePacked(ROOT_NODE, labelHash)); address subdomainOwner = ensRegistry.owner(childNode); require(subdomainOwner != address(0x0), "TALSUBDOMAIN_REGISTRAR: SUBDOMAIN_NOT_REGISTERED"); ensRegistry.setSubnodeRecord(ROOT_NODE, labelHash, address(0x0), address(0x0), 0); } }
3,070,545
[ 1, 17516, 392, 512, 3156, 17450, 297, 716, 357, 3251, 720, 14180, 603, 12433, 6186, 434, 3675, 25937, 18, 12109, 2026, 1744, 279, 16242, 635, 4440, 1375, 4861, 68, 598, 326, 508, 434, 326, 2461, 2898, 14302, 358, 1744, 3613, 16, 471, 326, 1433, 1651, 434, 326, 16242, 2898, 2545, 358, 1744, 18, 1021, 17450, 297, 1508, 25718, 279, 4143, 805, 5039, 16, 1492, 17385, 1375, 4793, 68, 20286, 358, 326, 394, 3410, 16, 471, 1678, 326, 1375, 8443, 68, 2236, 487, 326, 3410, 434, 326, 16242, 316, 512, 3156, 18, 385, 583, 6478, 16, 333, 6835, 1552, 486, 866, 1245, 498, 1272, 434, 279, 12889, 2461, 30, 300, 2585, 326, 508, 4732, 55, 8749, 2212, 5918, 35, 2177, 12165, 10685, 866, 4259, 2795, 2186, 364, 1517, 2461, 1865, 10067, 310, 2182, 358, 3677, 364, 7914, 18, 4257, 87, 1410, 2719, 1230, 866, 716, 326, 10128, 2898, 854, 10067, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 399, 287, 1676, 4308, 30855, 353, 14223, 6914, 16, 24142, 287, 30855, 1358, 288, 203, 565, 1731, 1578, 1071, 11732, 11011, 67, 8744, 31, 203, 203, 565, 512, 3156, 1071, 19670, 4243, 31, 203, 565, 7224, 4301, 1071, 1071, 4301, 31, 203, 565, 8858, 30855, 1071, 6605, 30855, 31, 203, 565, 10594, 639, 58, 23, 1358, 2713, 6205, 8141, 31, 203, 565, 2254, 5034, 1071, 16242, 14667, 31, 203, 565, 1426, 1071, 9627, 273, 629, 31, 203, 203, 565, 2254, 5034, 2713, 5381, 490, 1506, 273, 404, 73, 2643, 31, 203, 203, 565, 3885, 12, 203, 3639, 512, 3156, 19670, 16, 203, 3639, 7224, 4301, 5039, 16, 203, 3639, 8858, 30855, 17450, 297, 16, 203, 3639, 10594, 639, 58, 23, 1358, 6205, 8141, 1887, 16, 203, 3639, 1731, 1578, 756, 16, 203, 3639, 1758, 6835, 5541, 16, 203, 3639, 2254, 5034, 2172, 1676, 4308, 14667, 203, 5666, 288, 4782, 4301, 97, 628, 8787, 773, 14180, 19, 773, 17, 16351, 87, 19, 16351, 87, 19, 7818, 2496, 19, 4782, 4301, 18, 18281, 14432, 203, 5666, 288, 11602, 30855, 97, 628, 8787, 773, 14180, 19, 773, 17, 16351, 87, 19, 16351, 87, 19, 14926, 1574, 3337, 297, 19, 11602, 30855, 18, 18281, 14432, 203, 5666, 288, 21951, 97, 628, 8787, 773, 14180, 19, 773, 17, 16351, 87, 19, 16351, 87, 19, 9893, 19, 21951, 18, 18281, 14432, 203, 5666, 288, 11602, 11944, 97, 628, 8787, 773, 14180, 19, 773, 17, 16351, 87, 19, 16351, 87, 19, 14926, 3321, 17, 280, 16066, 19, 11602, 11944, 18, 2 ]
./full_match/4/0x1c61036cC816606EFb7754e9D9774649d70a2Ab5/sources/contracts/Dragon.sol
address owner _dragon.owner
function getDragon(uint256 _dragonId) public view returns ( uint256 dragonId, string memory name, uint256 generation, uint256 fatherId, uint256 motherId, bool gender, uint8 color, uint8 level, genes memory dominantGenes, genes memory recesiveGenes1, genes memory recesiveGenes2, uint256 lastBirthDate ) { dragon memory _dragon = dragons[_dragonId]; return ( _dragon.dragonId, _dragon.name, _dragon.generation, _dragon.fatherId, _dragon.motherId, _dragon.gender, _dragon.color, _dragon.level, _dragon.dominantGenes, _dragon.recesiveGenes1, _dragon.recesiveGenes2, _dragon.lastBirthDate ); }
12,345,908
[ 1, 2867, 3410, 389, 15997, 265, 18, 8443, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2343, 2458, 265, 12, 11890, 5034, 389, 15997, 265, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 8823, 265, 548, 16, 203, 5411, 533, 3778, 508, 16, 203, 5411, 2254, 5034, 9377, 16, 203, 5411, 2254, 5034, 284, 4806, 548, 16, 203, 5411, 2254, 5034, 312, 3011, 548, 16, 203, 5411, 1426, 18578, 16, 203, 5411, 2254, 28, 2036, 16, 203, 5411, 2254, 28, 1801, 16, 203, 5411, 11423, 3778, 4092, 20030, 7642, 281, 16, 203, 5411, 11423, 3778, 283, 764, 688, 7642, 281, 21, 16, 203, 5411, 11423, 3778, 283, 764, 688, 7642, 281, 22, 16, 203, 5411, 2254, 5034, 1142, 25791, 1626, 203, 3639, 262, 203, 565, 288, 203, 3639, 8823, 265, 3778, 389, 15997, 265, 273, 8823, 7008, 63, 67, 15997, 265, 548, 15533, 203, 3639, 327, 261, 203, 5411, 389, 15997, 265, 18, 15997, 265, 548, 16, 203, 5411, 389, 15997, 265, 18, 529, 16, 203, 5411, 389, 15997, 265, 18, 25514, 16, 203, 5411, 389, 15997, 265, 18, 74, 4806, 548, 16, 203, 5411, 389, 15997, 265, 18, 81, 3011, 548, 16, 203, 5411, 389, 15997, 265, 18, 27638, 16, 203, 5411, 389, 15997, 265, 18, 3266, 16, 203, 5411, 389, 15997, 265, 18, 2815, 16, 203, 5411, 389, 15997, 265, 18, 9859, 20030, 7642, 281, 16, 203, 5411, 389, 15997, 265, 18, 266, 764, 688, 7642, 281, 21, 16, 203, 5411, 389, 15997, 265, 18, 266, 764, 688, 7642, 281, 22, 16, 203, 5411, 389, 15997, 265, 18, 2 ]
pragma solidity ^0.4.18; contract DataSourceInterface { function isDataSource() public pure returns (bool); function getGroupResult(uint matchId) external; function getRoundOfSixteenTeams(uint index) external; function getRoundOfSixteenResult(uint matchId) external; function getQuarterResult(uint matchId) external; function getSemiResult(uint matchId) external; function getFinalTeams() external; function getYellowCards() external; function getRedCards() external; } /** * @title DataLayer. * @author CryptoCup Team (https://cryptocup.io/about) */ contract DataLayer{ uint256 constant WCCTOKEN_CREATION_LIMIT = 5000000; uint256 constant STARTING_PRICE = 45 finney; /// Epoch times based on when the prices change. uint256 constant FIRST_PHASE = 1527476400; uint256 constant SECOND_PHASE = 1528081200; uint256 constant THIRD_PHASE = 1528686000; uint256 constant WORLD_CUP_START = 1528945200; DataSourceInterface public dataSource; address public dataSourceAddress; address public adminAddress; uint256 public deploymentTime = 0; uint256 public gameFinishedTime = 0; //set this to now when oraclize was called. uint32 public lastCalculatedToken = 0; uint256 public pointsLimit = 0; uint32 public lastCheckedToken = 0; uint32 public winnerCounter = 0; uint32 public lastAssigned = 0; uint256 public auxWorstPoints = 500000000; uint32 public payoutRange = 0; uint32 public lastPrizeGiven = 0; uint256 public prizePool = 0; uint256 public adminPool = 0; uint256 public finalizedTime = 0; enum teamState { None, ROS, QUARTERS, SEMIS, FINAL } enum pointsValidationState { Unstarted, LimitSet, LimitCalculated, OrderChecked, TopWinnersAssigned, WinnersAssigned, Finished } /** * groups1 scores of the first half of matches (8 bits each) * groups2 scores of the second half of matches (8 bits each) * brackets winner&#39;s team ids of each round (5 bits each) * timeStamp creation timestamp * extra number of yellow and red cards (16 bits each) */ struct Token { uint192 groups1; uint192 groups2; uint160 brackets; uint64 timeStamp; uint32 extra; } struct GroupResult{ uint8 teamOneGoals; uint8 teamTwoGoals; } struct BracketPhase{ uint8[16] roundOfSixteenTeamsIds; mapping (uint8 => bool) teamExists; mapping (uint8 => teamState) middlePhaseTeamsIds; uint8[4] finalsTeamsIds; } struct Extras { uint16 yellowCards; uint16 redCards; } // List of all tokens Token[] tokens; GroupResult[48] groupsResults; BracketPhase bracketsResults; Extras extraResults; // List of all tokens that won uint256[] sortedWinners; // List of the worst tokens (they also win) uint256[] worstTokens; pointsValidationState public pValidationState = pointsValidationState.Unstarted; mapping (address => uint256[]) public tokensOfOwnerMap; mapping (uint256 => address) public ownerOfTokenMap; mapping (uint256 => address) public tokensApprovedMap; mapping (uint256 => uint256) public tokenToPayoutMap; mapping (uint256 => uint16) public tokenToPointsMap; event LogTokenBuilt(address creatorAddress, uint256 tokenId, Token token); event LogDataSourceCallbackList(uint8[] result); event LogDataSourceCallbackInt(uint8 result); event LogDataSourceCallbackTwoInt(uint8 result, uint8 result2); } ///Author Dieter Shirley (https://github.com/dete) contract ERC721 { event LogTransfer(address from, address to, uint256 tokenId); event LogApproval(address owner, address approved, uint256 tokenId); function name() public view returns (string); function symbol() public view returns (string); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); } /** * @title AccessControlLayer * @author CryptoCup Team (https://cryptocup.io/about) * @dev Containes basic admin modifiers to restrict access to some functions. Allows * for pauseing, and setting emergency stops. */ contract AccessControlLayer is DataLayer{ bool public paused = false; bool public finalized = false; bool public saleOpen = true; /** * @dev Main modifier to limit access to delicate functions. */ modifier onlyAdmin() { require(msg.sender == adminAddress); _; } /** * @dev Modifier that checks that the contract is not paused */ modifier isNotPaused() { require(!paused); _; } /** * @dev Modifier that checks that the contract is paused */ modifier isPaused() { require(paused); _; } /** * @dev Modifier that checks that the contract has finished successfully */ modifier hasFinished() { require((gameFinishedTime != 0) && now >= (gameFinishedTime + (15 days))); _; } /** * @dev Modifier that checks that the contract has finalized */ modifier hasFinalized() { require(finalized); _; } /** * @dev Checks if pValidationState is in the provided stats * @param state State required to run */ modifier checkState(pointsValidationState state){ require(pValidationState == state); _; } /** * @dev Transfer contract&#39;s ownership * @param _newAdmin Address to be set */ function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); adminAddress = _newAdmin; } /** * @dev Sets the contract pause state * @param state True to pause */ function setPauseState(bool state) external onlyAdmin { paused = state; } /** * @dev Sets the contract to finalized * @param state True to finalize */ function setFinalized(bool state) external onlyAdmin { paused = state; finalized = state; if(finalized == true) finalizedTime = now; } } /** * @title CryptoCupToken, main implemantations of the ERC721 standard * @author CryptoCup Team (https://cryptocup.io/about) */ contract CryptocupToken is AccessControlLayer, ERC721 { //FUNCTIONALTIY /** * @notice checks if a user owns a token * @param userAddress - The address to check. * @param tokenId - ID of the token that needs to be verified. * @return true if the userAddress provided owns the token. */ function _userOwnsToken(address userAddress, uint256 tokenId) internal view returns (bool){ return ownerOfTokenMap[tokenId] == userAddress; } /** * @notice checks if the address provided is approved for a given token * @param userAddress * @param tokenId * @return true if it is aproved */ function _tokenIsApproved(address userAddress, uint256 tokenId) internal view returns (bool) { return tokensApprovedMap[tokenId] == userAddress; } /** * @notice transfers the token specified from sneder address to receiver address. * @param fromAddress the sender address that initially holds the token. * @param toAddress the receipient of the token. * @param tokenId ID of the token that will be sent. */ function _transfer(address fromAddress, address toAddress, uint256 tokenId) internal { require(tokensOfOwnerMap[toAddress].length < 100); require(pValidationState == pointsValidationState.Unstarted); tokensOfOwnerMap[toAddress].push(tokenId); ownerOfTokenMap[tokenId] = toAddress; uint256[] storage tokenArray = tokensOfOwnerMap[fromAddress]; for (uint256 i = 0; i < tokenArray.length; i++){ if(tokenArray[i] == tokenId){ tokenArray[i] = tokenArray[tokenArray.length-1]; } } delete tokenArray[tokenArray.length-1]; tokenArray.length--; delete tokensApprovedMap[tokenId]; } /** * @notice Approve the address for a given token * @param tokenId - ID of token to be approved * @param userAddress - Address that will be approved */ function _approve(uint256 tokenId, address userAddress) internal { tokensApprovedMap[tokenId] = userAddress; } /** * @notice set token owner to an address * @dev sets token owner on the contract data structures * @param ownerAddress address to be set * @param tokenId Id of token to be used */ function _setTokenOwner(address ownerAddress, uint256 tokenId) internal{ tokensOfOwnerMap[ownerAddress].push(tokenId); ownerOfTokenMap[tokenId] = ownerAddress; } //ERC721 INTERFACE function name() public view returns (string){ return "Cryptocup"; } function symbol() public view returns (string){ return "CC"; } function balanceOf(address userAddress) public view returns (uint256 count) { return tokensOfOwnerMap[userAddress].length; } function transfer(address toAddress,uint256 tokenId) external isNotPaused { require(toAddress != address(0)); require(toAddress != address(this)); require(_userOwnsToken(msg.sender, tokenId)); _transfer(msg.sender, toAddress, tokenId); LogTransfer(msg.sender, toAddress, tokenId); } function transferFrom(address fromAddress, address toAddress, uint256 tokenId) external isNotPaused { require(toAddress != address(0)); require(toAddress != address(this)); require(_tokenIsApproved(msg.sender, tokenId)); require(_userOwnsToken(fromAddress, tokenId)); _transfer(fromAddress, toAddress, tokenId); LogTransfer(fromAddress, toAddress, tokenId); } function approve( address toAddress, uint256 tokenId) external isNotPaused { require(toAddress != address(0)); require(_userOwnsToken(msg.sender, tokenId)); _approve(tokenId, toAddress); LogApproval(msg.sender, toAddress, tokenId); } function totalSupply() public view returns (uint) { return tokens.length; } function ownerOf(uint256 tokenId) external view returns (address ownerAddress) { ownerAddress = ownerOfTokenMap[tokenId]; require(ownerAddress != address(0)); } function tokensOfOwner(address ownerAddress) external view returns(uint256[] tokenIds) { tokenIds = tokensOfOwnerMap[ownerAddress]; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title GameLogicLayer, contract in charge of everything related to calculating points, asigning * winners, and distributing prizes. * @author CryptoCup Team (https://cryptocup.io/about) */ contract GameLogicLayer is CryptocupToken{ using SafeMath for *; uint8 TEAM_RESULT_MASK_GROUPS = 15; uint160 RESULT_MASK_BRACKETS = 31; uint16 EXTRA_MASK_BRACKETS = 65535; uint16 private lastPosition; uint16 private superiorQuota; uint16[] private payDistributionAmount = [1,1,1,1,1,1,1,1,1,1,5,5,10,20,50,100,100,200,500,1500,2500]; uint32[] private payoutDistribution; event LogGroupDataArrived(uint matchId, uint8 result, uint8 result2); event LogRoundOfSixteenArrived(uint id, uint8 result); event LogMiddlePhaseArrived(uint matchId, uint8 result); event LogFinalsArrived(uint id, uint8[4] result); event LogExtrasArrived(uint id, uint16 result); //ORACLIZE function dataSourceGetGroupResult(uint matchId) external onlyAdmin{ dataSource.getGroupResult(matchId); } function dataSourceGetRoundOfSixteen(uint index) external onlyAdmin{ dataSource.getRoundOfSixteenTeams(index); } function dataSourceGetRoundOfSixteenResult(uint matchId) external onlyAdmin{ dataSource.getRoundOfSixteenResult(matchId); } function dataSourceGetQuarterResult(uint matchId) external onlyAdmin{ dataSource.getQuarterResult(matchId); } function dataSourceGetSemiResult(uint matchId) external onlyAdmin{ dataSource.getSemiResult(matchId); } function dataSourceGetFinals() external onlyAdmin{ dataSource.getFinalTeams(); } function dataSourceGetYellowCards() external onlyAdmin{ dataSource.getYellowCards(); } function dataSourceGetRedCards() external onlyAdmin{ dataSource.getRedCards(); } /** * @notice sets a match result to the contract storage * @param matchId id of match to check * @param result number of goals the first team scored * @param result2 number of goals the second team scored */ function dataSourceCallbackGroup(uint matchId, uint8 result, uint8 result2) public { require (msg.sender == dataSourceAddress); require (matchId >= 0 && matchId <= 47); groupsResults[matchId].teamOneGoals = result; groupsResults[matchId].teamTwoGoals = result2; LogGroupDataArrived(matchId, result, result2); } /** * @notice sets the sixteen teams that made it through groups to the contract storage * @param id index of sixteen teams * @param result results to be set */ function dataSourceCallbackRoundOfSixteen(uint id, uint8 result) public { require (msg.sender == dataSourceAddress); bracketsResults.roundOfSixteenTeamsIds[id] = result; bracketsResults.teamExists[result] = true; LogRoundOfSixteenArrived(id, result); } function dataSourceCallbackTeamId(uint matchId, uint8 result) public { require (msg.sender == dataSourceAddress); teamState state = bracketsResults.middlePhaseTeamsIds[result]; if (matchId >= 48 && matchId <= 55){ if (state < teamState.ROS) bracketsResults.middlePhaseTeamsIds[result] = teamState.ROS; } else if (matchId >= 56 && matchId <= 59){ if (state < teamState.QUARTERS) bracketsResults.middlePhaseTeamsIds[result] = teamState.QUARTERS; } else if (matchId == 60 || matchId == 61){ if (state < teamState.SEMIS) bracketsResults.middlePhaseTeamsIds[result] = teamState.SEMIS; } LogMiddlePhaseArrived(matchId, result); } /** * @notice sets the champion, second, third and fourth teams to the contract storage * @param id * @param result ids of the four teams */ function dataSourceCallbackFinals(uint id, uint8[4] result) public { require (msg.sender == dataSourceAddress); uint256 i; for(i = 0; i < 4; i++){ bracketsResults.finalsTeamsIds[i] = result[i]; } LogFinalsArrived(id, result); } /** * @notice sets the number of cards to the contract storage * @param id 101 for yellow cards, 102 for red cards * @param result amount of cards */ function dataSourceCallbackExtras(uint id, uint16 result) public { require (msg.sender == dataSourceAddress); if (id == 101){ extraResults.yellowCards = result; } else if (id == 102){ extraResults.redCards = result; } LogExtrasArrived(id, result); } /** * @notice check if prediction for a match winner is correct * @param realResultOne amount of goals team one scored * @param realResultTwo amount of goals team two scored * @param tokenResultOne amount of goals team one was predicted to score * @param tokenResultTwo amount of goals team two was predicted to score * @return */ function matchWinnerOk(uint8 realResultOne, uint8 realResultTwo, uint8 tokenResultOne, uint8 tokenResultTwo) internal pure returns(bool){ int8 realR = int8(realResultOne - realResultTwo); int8 tokenR = int8(tokenResultOne - tokenResultTwo); return (realR > 0 && tokenR > 0) || (realR < 0 && tokenR < 0) || (realR == 0 && tokenR == 0); } /** * @notice get points from a single match * @param matchIndex * @param groupsPhase token predictions * @return 10 if predicted score correctly, 3 if predicted only who would win * and 0 if otherwise */ function getMatchPointsGroups (uint256 matchIndex, uint192 groupsPhase) internal view returns(uint16 matchPoints) { uint8 tokenResultOne = uint8(groupsPhase & TEAM_RESULT_MASK_GROUPS); uint8 tokenResultTwo = uint8((groupsPhase >> 4) & TEAM_RESULT_MASK_GROUPS); uint8 teamOneGoals = groupsResults[matchIndex].teamOneGoals; uint8 teamTwoGoals = groupsResults[matchIndex].teamTwoGoals; if (teamOneGoals == tokenResultOne && teamTwoGoals == tokenResultTwo){ matchPoints += 10; } else { if (matchWinnerOk(teamOneGoals, teamTwoGoals, tokenResultOne, tokenResultTwo)){ matchPoints += 3; } } } /** * @notice calculates points from the last two matches * @param brackets token predictions * @return amount of points gained from the last two matches */ function getFinalRoundPoints (uint160 brackets) internal view returns(uint16 finalRoundPoints) { uint8[3] memory teamsIds; for (uint i = 0; i <= 2; i++){ brackets = brackets >> 5; //discard 4th place teamsIds[2-i] = uint8(brackets & RESULT_MASK_BRACKETS); } if (teamsIds[0] == bracketsResults.finalsTeamsIds[0]){ finalRoundPoints += 100; } if (teamsIds[2] == bracketsResults.finalsTeamsIds[2]){ finalRoundPoints += 25; } if (teamsIds[0] == bracketsResults.finalsTeamsIds[1]){ finalRoundPoints += 50; } if (teamsIds[1] == bracketsResults.finalsTeamsIds[0] || teamsIds[1] == bracketsResults.finalsTeamsIds[1]){ finalRoundPoints += 50; } } /** * @notice calculates points for round of sixteen, quarter-finals and semifinals * @param size amount of matches in round * @param round ros, qf, sf or f * @param brackets predictions * @return amount of points */ function getMiddleRoundPoints(uint8 size, teamState round, uint160 brackets) internal view returns(uint16 middleRoundResults){ uint8 teamId; for (uint i = 0; i < size; i++){ teamId = uint8(brackets & RESULT_MASK_BRACKETS); if (uint(bracketsResults.middlePhaseTeamsIds[teamId]) >= uint(round) ) { middleRoundResults+=60; } brackets = brackets >> 5; } } /** * @notice calculates points for correct predictions of group winners * @param brackets token predictions * @return amount of points */ function getQualifiersPoints(uint160 brackets) internal view returns(uint16 qualifiersPoints){ uint8 teamId; for (uint256 i = 0; i <= 15; i++){ teamId = uint8(brackets & RESULT_MASK_BRACKETS); if (teamId == bracketsResults.roundOfSixteenTeamsIds[15-i]){ qualifiersPoints+=30; } else if (bracketsResults.teamExists[teamId]){ qualifiersPoints+=25; } brackets = brackets >> 5; } } /** * @notice calculates points won by yellow and red cards predictions * @param extras token predictions * @return amount of points */ function getExtraPoints(uint32 extras) internal view returns(uint16 extraPoints){ uint16 redCards = uint16(extras & EXTRA_MASK_BRACKETS); extras = extras >> 16; uint16 yellowCards = uint16(extras); if (redCards == extraResults.redCards){ extraPoints+=20; } if (yellowCards == extraResults.yellowCards){ extraPoints+=20; } } /** * @notice calculates total amount of points for a token * @param t token to calculate points for * @return total amount of points */ function calculateTokenPoints (Token memory t) internal view returns(uint16 points){ //Groups phase 1 uint192 g1 = t.groups1; for (uint256 i = 0; i <= 23; i++){ points+=getMatchPointsGroups(23-i, g1); g1 = g1 >> 8; } //Groups phase 2 uint192 g2 = t.groups2; for (i = 0; i <= 23; i++){ points+=getMatchPointsGroups(47-i, g2); g2 = g2 >> 8; } uint160 bracketsLocal = t.brackets; //Brackets phase 1 points+=getFinalRoundPoints(bracketsLocal); bracketsLocal = bracketsLocal >> 20; //Brackets phase 2 points+=getMiddleRoundPoints(4, teamState.QUARTERS, bracketsLocal); bracketsLocal = bracketsLocal >> 20; //Brackets phase 3 points+=getMiddleRoundPoints(8, teamState.ROS, bracketsLocal); bracketsLocal = bracketsLocal >> 40; //Brackets phase 4 points+=getQualifiersPoints(bracketsLocal); //Extras points+=getExtraPoints(t.extra); } /** * @notice Sets the points of all the tokens between the last chunk set and the amount given. * @dev This function uses all the data collected earlier by oraclize to calculate points. * @param amount The amount of tokens that should be analyzed. */ function calculatePointsBlock(uint32 amount) external{ require (gameFinishedTime == 0); require(amount + lastCheckedToken <= tokens.length); for (uint256 i = lastCalculatedToken; i < (lastCalculatedToken + amount); i++) { uint16 points = calculateTokenPoints(tokens[i]); tokenToPointsMap[i] = points; if(worstTokens.length == 0 || points <= auxWorstPoints){ if(worstTokens.length != 0 && points < auxWorstPoints){ worstTokens.length = 0; } if(worstTokens.length < 100){ auxWorstPoints = points; worstTokens.push(i); } } } lastCalculatedToken += amount; } /** * @notice Sets the structures for payout distribution, last position and superior quota. Payout distribution is the * percentage of the pot each position gets, last position is the percentage of the pot the last position gets, * and superior quota is the total amount OF winners that are given a prize. * @dev Each of this structures is dynamic and is assigned depending on the total amount of tokens in the game */ function setPayoutDistributionId () internal { if(tokens.length < 101){ payoutDistribution = [289700, 189700, 120000, 92500, 75000, 62500, 52500, 42500, 40000, 35600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; lastPosition = 0; superiorQuota = 10; }else if(tokens.length < 201){ payoutDistribution = [265500, 165500, 105500, 75500, 63000, 48000, 35500, 20500, 20000, 19500, 18500, 17800, 0, 0, 0, 0, 0, 0, 0, 0, 0]; lastPosition = 0; superiorQuota = 20; }else if(tokens.length < 301){ payoutDistribution = [260700, 155700, 100700, 70900, 60700, 45700, 35500, 20500, 17900, 12500, 11500, 11000, 10670, 0, 0, 0, 0, 0, 0, 0, 0]; lastPosition = 0; superiorQuota = 30; }else if(tokens.length < 501){ payoutDistribution = [238600, 138600, 88800, 63800, 53800, 43800, 33800, 18800, 17500, 12500, 9500, 7500, 7100, 6700, 0, 0, 0, 0, 0, 0, 0]; lastPosition = 0; superiorQuota = 50; }else if(tokens.length < 1001){ payoutDistribution = [218300, 122300, 72300, 52400, 43900, 33900, 23900, 16000, 13000, 10000, 9000, 7000, 5000, 4000, 3600, 0, 0, 0, 0, 0, 0]; lastPosition = 4000; superiorQuota = 100; }else if(tokens.length < 2001){ payoutDistribution = [204500, 114000, 64000, 44100, 35700, 26700, 22000, 15000, 11000, 9500, 8500, 6500, 4600, 2500, 2000, 1800, 0, 0, 0, 0, 0]; lastPosition = 2500; superiorQuota = 200; }else if(tokens.length < 3001){ payoutDistribution = [189200, 104800, 53900, 34900, 29300, 19300, 15300, 14000, 10500, 8300, 8000, 6000, 3800, 2500, 2000, 1500, 1100, 0, 0, 0, 0]; lastPosition = 2500; superiorQuota = 300; }else if(tokens.length < 5001){ payoutDistribution = [178000, 100500, 47400, 30400, 24700, 15500, 15000, 12000, 10200, 7800, 7400, 5500, 3300, 2000, 1500, 1200, 900, 670, 0, 0, 0]; lastPosition = 2000; superiorQuota = 500; }else if(tokens.length < 10001){ payoutDistribution = [157600, 86500, 39000, 23100, 18900, 15000, 14000, 11000, 9300, 6100, 6000, 5000, 3800, 1500, 1100, 900, 700, 500, 360, 0, 0]; lastPosition = 1500; superiorQuota = 1000; }else if(tokens.length < 25001){ payoutDistribution = [132500, 70200, 31300, 18500, 17500, 14000, 13500, 10500, 7500, 5500, 5000, 4000, 3000, 1000, 900, 700, 600, 400, 200, 152, 0]; lastPosition = 1000; superiorQuota = 2500; } else { payoutDistribution = [120000, 63000, 27000, 18800, 17300, 13700, 13000, 10000, 6300, 5000, 4500, 3900, 2500, 900, 800, 600, 500, 350, 150, 100, 70]; lastPosition = 900; superiorQuota = 5000; } } /** * @notice Sets the id of the last token that will be given a prize. * @dev This is done to offload some of the calculations needed for sorting, and to cap the number of sorts * needed to just the winners and not the whole array of tokens. * @param tokenId last token id */ function setLimit(uint256 tokenId) external onlyAdmin{ require(tokenId < tokens.length); require(pValidationState == pointsValidationState.Unstarted || pValidationState == pointsValidationState.LimitSet); pointsLimit = tokenId; pValidationState = pointsValidationState.LimitSet; lastCheckedToken = 0; lastCalculatedToken = 0; winnerCounter = 0; setPayoutDistributionId(); } /** * @notice Sets the 10th percentile of the sorted array of points * @param amount tokens in a chunk */ function calculateWinners(uint32 amount) external onlyAdmin checkState(pointsValidationState.LimitSet){ require(amount + lastCheckedToken <= tokens.length); uint256 points = tokenToPointsMap[pointsLimit]; for(uint256 i = lastCheckedToken; i < lastCheckedToken + amount; i++){ if(tokenToPointsMap[i] > points || (tokenToPointsMap[i] == points && i <= pointsLimit)){ winnerCounter++; } } lastCheckedToken += amount; if(lastCheckedToken == tokens.length){ require(superiorQuota == winnerCounter); pValidationState = pointsValidationState.LimitCalculated; } } /** * @notice Checks if the order given offchain coincides with the order of the actual previously calculated points * in the smart contract. * @dev the token sorting is done offchain so as to save on the huge amount of gas and complications that * could occur from doing all the sorting onchain. * @param sortedChunk chunk sorted by points */ function checkOrder(uint32[] sortedChunk) external onlyAdmin checkState(pointsValidationState.LimitCalculated){ require(sortedChunk.length + sortedWinners.length <= winnerCounter); for(uint256 i=0;i < sortedChunk.length-1;i++){ uint256 id = sortedChunk[i]; uint256 sigId = sortedChunk[i+1]; require(tokenToPointsMap[id] > tokenToPointsMap[sigId] || (tokenToPointsMap[id] == tokenToPointsMap[sigId] && id < sigId)); } if(sortedWinners.length != 0){ uint256 id2 = sortedWinners[sortedWinners.length-1]; uint256 sigId2 = sortedChunk[0]; require(tokenToPointsMap[id2] > tokenToPointsMap[sigId2] || (tokenToPointsMap[id2] == tokenToPointsMap[sigId2] && id2 < sigId2)); } for(uint256 j=0;j < sortedChunk.length;j++){ sortedWinners.push(sortedChunk[j]); } if(sortedWinners.length == winnerCounter){ require(sortedWinners[sortedWinners.length-1] == pointsLimit); pValidationState = pointsValidationState.OrderChecked; } } /** * @notice If anything during the point calculation and sorting part should fail, this function can reset * data structures to their initial position, so as to */ function resetWinners(uint256 newLength) external onlyAdmin checkState(pointsValidationState.LimitCalculated){ sortedWinners.length = newLength; } /** * @notice Assigns prize percentage for the lucky top 30 winners. Each token will be assigned a uint256 inside * tokenToPayoutMap structure that represents the size of the pot that belongs to that token. If any tokens * tie inside of the first 30 tokens, the prize will be summed and divided equally. */ function setTopWinnerPrizes() external onlyAdmin checkState(pointsValidationState.OrderChecked){ uint256 percent = 0; uint[] memory tokensEquals = new uint[](30); uint16 tokenEqualsCounter = 0; uint256 currentTokenId; uint256 currentTokenPoints; uint256 lastTokenPoints; uint32 counter = 0; uint256 maxRange = 13; if(tokens.length < 201){ maxRange = 10; } while(payoutRange < maxRange){ uint256 inRangecounter = payDistributionAmount[payoutRange]; while(inRangecounter > 0){ currentTokenId = sortedWinners[counter]; currentTokenPoints = tokenToPointsMap[currentTokenId]; inRangecounter--; //Special case for the last one if(inRangecounter == 0 && payoutRange == maxRange - 1){ if(currentTokenPoints == lastTokenPoints){ percent += payoutDistribution[payoutRange]; tokensEquals[tokenEqualsCounter] = currentTokenId; tokenEqualsCounter++; }else{ tokenToPayoutMap[currentTokenId] = payoutDistribution[payoutRange]; } } if(counter != 0 && (currentTokenPoints != lastTokenPoints || (inRangecounter == 0 && payoutRange == maxRange - 1))){ //Fix second condition for(uint256 i=0;i < tokenEqualsCounter;i++){ tokenToPayoutMap[tokensEquals[i]] = percent.div(tokenEqualsCounter); } percent = 0; tokensEquals = new uint[](30); tokenEqualsCounter = 0; } percent += payoutDistribution[payoutRange]; tokensEquals[tokenEqualsCounter] = currentTokenId; tokenEqualsCounter++; counter++; lastTokenPoints = currentTokenPoints; } payoutRange++; } pValidationState = pointsValidationState.TopWinnersAssigned; lastPrizeGiven = counter; } /** * @notice Sets prize percentage to every address that wins from the position 30th onwards * @dev If there are less than 300 tokens playing, then this function will set nothing. * @param amount tokens in a chunk */ function setWinnerPrizes(uint32 amount) external onlyAdmin checkState(pointsValidationState.TopWinnersAssigned){ require(lastPrizeGiven + amount <= winnerCounter); uint16 inRangeCounter = payDistributionAmount[payoutRange]; for(uint256 i = 0; i < amount; i++){ if (inRangeCounter == 0){ payoutRange++; inRangeCounter = payDistributionAmount[payoutRange]; } uint256 tokenId = sortedWinners[i + lastPrizeGiven]; tokenToPayoutMap[tokenId] = payoutDistribution[payoutRange]; inRangeCounter--; } //i + amount prize was not given yet, so amount -1 lastPrizeGiven += amount; payDistributionAmount[payoutRange] = inRangeCounter; if(lastPrizeGiven == winnerCounter){ pValidationState = pointsValidationState.WinnersAssigned; return; } } /** * @notice Sets prizes for last tokens and sets prize pool amount */ function setLastPositions() external onlyAdmin checkState(pointsValidationState.WinnersAssigned){ for(uint256 j = 0;j < worstTokens.length;j++){ uint256 tokenId = worstTokens[j]; tokenToPayoutMap[tokenId] += lastPosition.div(worstTokens.length); } uint256 balance = address(this).balance; adminPool = balance.mul(25).div(100); prizePool = balance.mul(75).div(100); pValidationState = pointsValidationState.Finished; gameFinishedTime = now; } } /** * @title CoreLayer * @author CryptoCup Team (https://cryptocup.io/about) * @notice Main contract */ contract CoreLayer is GameLogicLayer { function CoreLayer() public { adminAddress = msg.sender; deploymentTime = now; } /** * @dev Only accept eth from the admin */ function() external payable { require(msg.sender == adminAddress); } function isDataSourceCallback() public pure returns (bool){ return true; } /** * @notice Builds ERC721 token with the predictions provided by the user. * @param groups1 - First half of the group matches scores encoded in a uint192. * @param groups2 - Second half of the groups matches scores encoded in a uint192. * @param brackets - Bracket information encoded in a uint160. * @param extra - Extra information (number of red cards and yellow cards) encoded in a uint32. * @dev An automatic timestamp is added for internal use. */ function buildToken(uint192 groups1, uint192 groups2, uint160 brackets, uint32 extra) external payable isNotPaused { Token memory token = Token({ groups1: groups1, groups2: groups2, brackets: brackets, timeStamp: uint64(now), extra: extra }); require(msg.value >= _getTokenPrice()); require(msg.sender != address(0)); require(tokens.length < WCCTOKEN_CREATION_LIMIT); require(tokensOfOwnerMap[msg.sender].length < 100); require(now < WORLD_CUP_START); //World cup Start uint256 tokenId = tokens.push(token) - 1; require(tokenId == uint256(uint32(tokenId))); _setTokenOwner(msg.sender, tokenId); LogTokenBuilt(msg.sender, tokenId, token); } /** * @param tokenId - ID of token to get. * @return Returns all the valuable information about a specific token. */ function getToken(uint256 tokenId) external view returns (uint192 groups1, uint192 groups2, uint160 brackets, uint64 timeStamp, uint32 extra) { Token storage token = tokens[tokenId]; groups1 = token.groups1; groups2 = token.groups2; brackets = token.brackets; timeStamp = token.timeStamp; extra = token.extra; } /** * @notice Called by the development team once the World Cup has ended (adminPool is set) * @dev Allows dev team to retrieve adminPool */ function adminWithdrawBalance() external onlyAdmin { adminAddress.transfer(adminPool); adminPool = 0; } /** * @notice Allows any user to retrieve their asigned prize. This would be the sum of the price of all the tokens * owned by the caller of this function. * @dev If the caller has no prize, the function will revert costing no gas to the caller. */ function withdrawPrize() external checkState(pointsValidationState.Finished){ uint256 prize = 0; uint256[] memory tokenList = tokensOfOwnerMap[msg.sender]; for(uint256 i = 0;i < tokenList.length; i++){ prize += tokenToPayoutMap[tokenList[i]]; tokenToPayoutMap[tokenList[i]] = 0; } require(prize > 0); msg.sender.transfer((prizePool.mul(prize)).div(1000000)); } /** * @notice Gets current token price */ function _getTokenPrice() internal view returns(uint256 tokenPrice){ if ( now >= THIRD_PHASE){ tokenPrice = (150 finney); } else if (now >= SECOND_PHASE) { tokenPrice = (110 finney); } else if (now >= FIRST_PHASE) { tokenPrice = (75 finney); } else { tokenPrice = STARTING_PRICE; } require(tokenPrice >= STARTING_PRICE && tokenPrice <= (200 finney)); } /** * @dev Sets the data source contract address * @param _address Address to be set */ function setDataSourceAddress(address _address) external onlyAdmin { DataSourceInterface c = DataSourceInterface(_address); require(c.isDataSource()); dataSource = c; dataSourceAddress = _address; } /** * @notice Testing function to corroborate group data from oraclize call * @param x Id of the match to get * @return uint8 Team 1 goals * @return uint8 Team 2 goals */ function getGroupData(uint x) external view returns(uint8 a, uint8 b){ a = groupsResults[x].teamOneGoals; b = groupsResults[x].teamTwoGoals; } /** * @notice Testing function to corroborate round of sixteen data from oraclize call * @return An array with the ids of the round of sixteen teams */ function getBracketData() external view returns(uint8[16] a){ a = bracketsResults.roundOfSixteenTeamsIds; } /** * @notice Testing function to corroborate brackets data from oraclize call * @param x Team id * @return The place the team reached */ function getBracketDataMiddleTeamIds(uint8 x) external view returns(teamState a){ a = bracketsResults.middlePhaseTeamsIds[x]; } /** * @notice Testing function to corroborate finals data from oraclize call * @return the 4 (four) final teams ids */ function getBracketDataFinals() external view returns(uint8[4] a){ a = bracketsResults.finalsTeamsIds; } /** * @notice Testing function to corroborate extra data from oraclize call * @return amount of yellow and red cards */ function getExtrasData() external view returns(uint16 a, uint16 b){ a = extraResults.yellowCards; b = extraResults.redCards; } //EMERGENCY CALLS //If something goes wrong or fails, these functions will allow retribution for token holders /** * @notice if there is an unresolvable problem, users can call to this function to get a refund. */ function emergencyWithdraw() external hasFinalized{ uint256 balance = STARTING_PRICE * tokensOfOwnerMap[msg.sender].length; delete tokensOfOwnerMap[msg.sender]; msg.sender.transfer(balance); } /** * @notice Let the admin cash-out the entire contract balance 10 days after game has finished. */ function finishedGameWithdraw() external onlyAdmin hasFinished{ uint256 balance = address(this).balance; adminAddress.transfer(balance); } /** * @notice Let the admin cash-out the entire contract balance 10 days after game has finished. */ function emergencyWithdrawAdmin() external hasFinalized onlyAdmin{ require(finalizedTime != 0 && now >= finalizedTime + 10 days ); msg.sender.transfer(address(this).balance); } }
* @notice set token owner to an address @dev sets token owner on the contract data structures @param ownerAddress address to be set @param tokenId Id of token to be used/
function _setTokenOwner(address ownerAddress, uint256 tokenId) internal{ tokensOfOwnerMap[ownerAddress].push(tokenId); ownerOfTokenMap[tokenId] = ownerAddress; }
7,712,456
[ 1, 542, 1147, 3410, 358, 392, 1758, 225, 1678, 1147, 3410, 603, 326, 6835, 501, 12597, 225, 3410, 1887, 1758, 358, 506, 444, 225, 1147, 548, 3124, 434, 1147, 358, 506, 1399, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 542, 1345, 5541, 12, 2867, 3410, 1887, 16, 2254, 5034, 1147, 548, 13, 2713, 95, 203, 203, 377, 202, 7860, 951, 5541, 863, 63, 8443, 1887, 8009, 6206, 12, 2316, 548, 1769, 203, 1377, 3410, 951, 1345, 863, 63, 2316, 548, 65, 273, 3410, 1887, 31, 203, 377, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; contract Pedersen { //uint public q = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint private q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint private gX = 19823850254741169819033785099293761935467223354323761392354670518001715552183; uint private gY = 15097907474011103550430959168661954736283086276546887690628027914974507414020; uint private hX = 3184834430741071145030522771540763108892281233703148152311693391954704539228; uint private hY = 1405615944858121891163559530323310827496899969303520166098610312148921359100; function Commit(uint b, uint r) public returns (uint cX, uint cY) { var (cX1, cY1) = ecMul(b, gX, gY); var (cX2, cY2) = ecMul(r, hX, hY); (cX, cY) = ecAdd(cX1, cY1, cX2, cY2); } function Verify(uint b, uint r, uint cX, uint cY) public returns (bool) { var (cX2, cY2) = Commit(b,r); return cX == cX2 && cY == cY2; } function CommitDelta(uint cX1, uint cY1, uint cX2, uint cY2) public returns (uint cX, uint cY) { (cX, cY) = ecAdd(cX1, cY1, cX2, q-cY2); } function ecMul(uint b, uint cX1, uint cY1) private returns (uint cX2, uint cY2) { bool success = false; bytes memory input = new bytes(96); bytes memory output = new bytes(64); assembly { mstore(add(input, 32), cX1) mstore(add(input, 64), cY1) mstore(add(input, 96), b) success := call(gas(), 7, 0, add(input, 32), 96, add(output, 32), 64) cX2 := mload(add(output, 32)) cY2 := mload(add(output, 64)) } require(success); } function ecAdd(uint cX1, uint cY1, uint cX2, uint cY2) public returns (uint cX3, uint cY3) { bool success = false; bytes memory input = new bytes(128); bytes memory output = new bytes(64); assembly { mstore(add(input, 32), cX1) mstore(add(input, 64), cY1) mstore(add(input, 96), cX2) mstore(add(input, 128), cY2) success := call(gas(), 6, 0, add(input, 32), 128, add(output, 32), 64) cX3 := mload(add(output, 32)) cY3 := mload(add(output, 64)) } require(success); } } contract Auction { enum VerificationStates {Init, Challenge,ChallengeDelta, Verify, VerifyDelta, ValidWinner} struct Bidder { uint commitX; uint commitY; bytes cipher; bool validProofs; bool paidBack; bool existing; } Pedersen pedersen; bool withdrawLock; VerificationStates public states; address private challengedBidder; uint private challengeBlockNumber; bool private testing; //for fast testing without checking block intervals uint8 private K = 10; //number of multiple rounds per ZKP uint public Q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint public V = 5472060717959818805561601436314318772174077789324455915672259473661306552145; uint[] commits; uint[] deltaCommits; mapping(address => Bidder) public bidders; address[] public indexs; uint mask =1; //Auction Parameters address public auctioneerAddress; uint public bidBlockNumber; uint public revealBlockNumber; uint public winnerPaymentBlockNumber; uint public maxBiddersCount; uint public fairnessFees; string public auctioneerRSAPublicKey; //these values are set when the auctioneer determines the winner address public winner; uint public highestBid; //Constructor = Setting all Parameters and auctioneerAddress as well function Auction(uint _bidBlockNumber, uint _revealBlockNumber, uint _winnerPaymentBlockNumber, uint _maxBiddersCount, uint _fairnessFees, string _auctioneerRSAPublicKey, address pedersenAddress, uint8 k, bool _testing) public payable { require(msg.value >= _fairnessFees); auctioneerAddress = msg.sender; bidBlockNumber = block.number + _bidBlockNumber; revealBlockNumber = bidBlockNumber + _revealBlockNumber; winnerPaymentBlockNumber = revealBlockNumber + _winnerPaymentBlockNumber; maxBiddersCount = _maxBiddersCount; fairnessFees = _fairnessFees; auctioneerRSAPublicKey = _auctioneerRSAPublicKey; pedersen = Pedersen(pedersenAddress); K= k; testing = _testing; } function Bid(uint cX, uint cY) public payable { require(block.number < bidBlockNumber || testing); //during bidding Interval require(indexs.length < maxBiddersCount); //available slot require(msg.value >= fairnessFees); //paying fees require(bidders[msg.sender].existing == false); bidders[msg.sender] = Bidder(cX, cY,"", false, false,true); indexs.push(msg.sender); } function Reveal(bytes cipher) public { require(block.number < revealBlockNumber && block.number > bidBlockNumber || testing); require(bidders[msg.sender].existing ==true); //existing bidder bidders[msg.sender].cipher = cipher; } function ClaimWinner(address _winner, uint _bid, uint _r) public challengeByAuctioneer { require(states == VerificationStates.Init); require(bidders[_winner].existing == true); //existing bidder require(_bid < V); //valid bid require(pedersen.Verify(_bid, _r, bidders[_winner].commitX, bidders[_winner].commitY)); //valid open of winner's commit winner = _winner; highestBid = _bid; states = VerificationStates.Challenge; } function ZKPCommit(address y, uint[] _commits, uint[] _deltaCommits) public challengeByAuctioneer { require(states == VerificationStates.Challenge || testing); require(_commits.length == K *4); require(_commits.length == _deltaCommits.length); require(bidders[y].existing == true); //existing bidder challengedBidder = y; challengeBlockNumber = block.number; for(uint i=0; i< _commits.length; i++) if(commits.length == i) { commits.push(_commits[i]); deltaCommits.push(_deltaCommits[i]); } else { commits[i] = _commits[i]; deltaCommits[i] = _deltaCommits[i]; } states = VerificationStates.Verify; } function ZKPVerify(uint[] response, uint[] deltaResponses) public challengeByAuctioneer { require(states == VerificationStates.Verify || states == VerificationStates.VerifyDelta); uint8 count =0; uint hash = uint(block.blockhash(challengeBlockNumber)); mask =1; uint i=0; uint j=0; uint cX; uint cY; while(i<response.length && j<commits.length) { if(hash&mask == 0) { require((response[i] + response[i+2])%Q==V); require(pedersen.Verify(response[i], response[i+1], commits[j], commits[j+1])); require(pedersen.Verify(response[i+2], response[i+3], commits[j+2], commits[j+3])); i+=4; } else { if(response[i+2] ==1) //z=1 (cX, cY) = pedersen.ecAdd(bidders[challengedBidder].commitX, bidders[challengedBidder].commitY, commits[j], commits[j+1]); else (cX, cY) = pedersen.ecAdd(bidders[challengedBidder].commitX, bidders[challengedBidder].commitY, commits[j+2], commits[j+3]); require(pedersen.Verify(response[i], response[i+1], cX, cY)); i+=3; } j+=4; mask = mask <<1; count++; } require(count==K); count =0; i =0; j=0; while(i<deltaResponses.length && j<deltaCommits.length) { if(hash&mask == 0) { require((deltaResponses[i] + deltaResponses[i+2])%Q==V); require(pedersen.Verify(deltaResponses[i], deltaResponses[i+1], deltaCommits[j], deltaCommits[j+1])); require(pedersen.Verify(deltaResponses[i+2], deltaResponses[i+3], deltaCommits[j+2], deltaCommits[j+3])); i+=4; } else { (cX, cY) = pedersen.CommitDelta(bidders[winner].commitX, bidders[winner].commitY, bidders[challengedBidder].commitX, bidders[challengedBidder].commitY); if(deltaResponses[i+2]==1) (cX, cY) = pedersen.ecAdd(cX,cY, deltaCommits[j], deltaCommits[j+1]); else (cX, cY) = pedersen.ecAdd(cX,cY, deltaCommits[j+2], deltaCommits[j+3]); require(pedersen.Verify(deltaResponses[i],deltaResponses[i+1],cX,cY)); i+=3; } j+=4; mask = mask <<1; count++; } require(count==K); bidders[challengedBidder].validProofs = true; states = VerificationStates.Challenge; } function VerifyAll() public challengeByAuctioneer { for (uint i = 0; i<indexs.length; i++) if(indexs[i] != winner) if(!bidders[indexs[i]].validProofs) { winner = 0; revert(); } states = VerificationStates.ValidWinner; } function Withdraw() public { require(states == VerificationStates.ValidWinner || block.number>winnerPaymentBlockNumber); require(msg.sender != winner); require(bidders[msg.sender].paidBack == false && bidders[msg.sender].existing == true); require(withdrawLock == false); withdrawLock = true; msg.sender.transfer(fairnessFees); bidders[msg.sender].paidBack = true; withdrawLock = false; } function WinnerPay() public payable { require(states == VerificationStates.ValidWinner); require(msg.sender == winner); require(msg.value >= highestBid - fairnessFees); } function Destroy() public { selfdestruct(auctioneerAddress); } modifier challengeByAuctioneer() { require(msg.sender == auctioneerAddress); //by auctioneer only require(block.number > revealBlockNumber && block.number < winnerPaymentBlockNumber || testing); //after reveal and before winner payment _; } } contract DutchAuction { /* * Events */ event BidSubmission(address indexed sender, uint256 amount); /* * Constants */ uint constant public MAX_TOKENS_SOLD = 9000000 * 10**18; // 9M uint constant public WAITING_PERIOD = 7 days; /* * Storage */ Token public gnosisToken; address public wallet; address public owner; uint public ceiling; uint public priceFactor; uint public startBlock; uint public endTime; uint public totalReceived; uint public finalPrice; mapping (address => uint) public bids; Stages public stage; /* * Enums */ enum Stages { AuctionDeployed, AuctionSetUp, AuctionStarted, AuctionEnded, TradingStarted } /* * Modifiers */ modifier atStage(Stages _stage) { if (stage != _stage) // Contract not in expected state throw; _; } modifier isOwner() { if (msg.sender != owner) // Only owner is allowed to proceed throw; _; } modifier isWallet() { if (msg.sender != wallet) // Only wallet is allowed to proceed throw; _; } modifier isValidPayload() { if (msg.data.length != 4 && msg.data.length != 36) throw; _; } modifier timedTransitions() { if (stage == Stages.AuctionStarted && calcTokenPrice() <= calcStopPrice()) finalizeAuction(); if (stage == Stages.AuctionEnded && now > endTime + WAITING_PERIOD) stage = Stages.TradingStarted; _; } /* * Public functions */ /// @dev Contract constructor function sets owner. /// @param _wallet Gnosis wallet. /// @param _ceiling Auction ceiling. /// @param _priceFactor Auction price factor. function DutchAuction(address _wallet, uint _ceiling, uint _priceFactor) public { if (_wallet == 0 || _ceiling == 0 || _priceFactor == 0) // Arguments are null. throw; owner = msg.sender; wallet = _wallet; ceiling = _ceiling; priceFactor = _priceFactor; stage = Stages.AuctionDeployed; } /// @dev Setup function sets external contracts' addresses. /// @param _gnosisToken Gnosis token address. function setup(address _gnosisToken) public isOwner atStage(Stages.AuctionDeployed) { if (_gnosisToken == 0) // Argument is null. throw; gnosisToken = Token(_gnosisToken); // Validate token balance if (gnosisToken.balanceOf(this) != MAX_TOKENS_SOLD) throw; stage = Stages.AuctionSetUp; } /// @dev Starts auction and sets startBlock. function startAuction() public isWallet atStage(Stages.AuctionSetUp) { stage = Stages.AuctionStarted; startBlock = block.number; } /// @dev Changes auction ceiling and start price factor before auction is started. /// @param _ceiling Updated auction ceiling. /// @param _priceFactor Updated start price factor. function changeSettings(uint _ceiling, uint _priceFactor) public isWallet atStage(Stages.AuctionSetUp) { ceiling = _ceiling; priceFactor = _priceFactor; } /// @dev Calculates current token price. /// @return Returns token price. function calcCurrentTokenPrice() public timedTransitions returns (uint) { if (stage == Stages.AuctionEnded || stage == Stages.TradingStarted) return finalPrice; return calcTokenPrice(); } /// @dev Returns correct stage, even if a function with timedTransitions modifier has not yet been called yet. /// @return Returns current auction stage. function updateStage() public timedTransitions returns (Stages) { return stage; } /// @dev Allows to send a bid to the auction. /// @param receiver Bid will be assigned to this address if set. function bid(address receiver) public payable isValidPayload timedTransitions atStage(Stages.AuctionStarted) returns (uint amount) { // If a bid is done on behalf of a user via ShapeShift, the receiver address is set. if (receiver == 0) receiver = msg.sender; amount = msg.value; // Prevent that more than 90% of tokens are sold. Only relevant if cap not reached. uint maxWei = (MAX_TOKENS_SOLD / 10**18) * calcTokenPrice() - totalReceived; uint maxWeiBasedOnTotalReceived = ceiling - totalReceived; if (maxWeiBasedOnTotalReceived < maxWei) maxWei = maxWeiBasedOnTotalReceived; // Only invest maximum possible amount. if (amount > maxWei) { amount = maxWei; // Send change back to receiver address. In case of a ShapeShift bid the user receives the change back directly. if (!receiver.send(msg.value - amount)) // Sending failed throw; } // Forward funding to ether wallet if (amount == 0 || !wallet.send(amount)) // No amount sent or sending failed throw; bids[receiver] += amount; totalReceived += amount; if (maxWei == amount) // When maxWei is equal to the big amount the auction is ended and finalizeAuction is triggered. finalizeAuction(); BidSubmission(receiver, amount); } /// @dev Claims tokens for bidder after auction. /// @param receiver Tokens will be assigned to this address if set. function claimTokens(address receiver) public isValidPayload timedTransitions atStage(Stages.TradingStarted) { if (receiver == 0) receiver = msg.sender; uint tokenCount = bids[receiver] * 10**18 / finalPrice; bids[receiver] = 0; gnosisToken.transfer(receiver, tokenCount); } /// @dev Calculates stop price. /// @return Returns stop price. function calcStopPrice() constant public returns (uint) { return totalReceived * 10**18 / MAX_TOKENS_SOLD + 1; } /// @dev Calculates token price. /// @return Returns token price. function calcTokenPrice() constant public returns (uint) { return priceFactor * 10**18 / (block.number - startBlock + 7500) + 1; } /* * Private functions */ function finalizeAuction() private { stage = Stages.AuctionEnded; if (totalReceived == ceiling) finalPrice = calcTokenPrice(); else finalPrice = calcStopPrice(); uint soldTokens = totalReceived * 10**18 / finalPrice; // Auction contract transfers all unsold tokens to Gnosis inventory multisig gnosisToken.transfer(wallet, MAX_TOKENS_SOLD - soldTokens); endTime = now; } }
@dev Setup function sets external contracts' addresses. @param _gnosisToken Gnosis token address. Argument is null. Validate token balance
function setup(address _gnosisToken) public isOwner atStage(Stages.AuctionDeployed) { if (_gnosisToken == 0) throw; gnosisToken = Token(_gnosisToken); if (gnosisToken.balanceOf(this) != MAX_TOKENS_SOLD) throw; stage = Stages.AuctionSetUp; }
6,346,041
[ 1, 7365, 445, 1678, 3903, 20092, 11, 6138, 18, 225, 389, 1600, 538, 291, 1345, 611, 18050, 291, 1147, 1758, 18, 5067, 353, 446, 18, 3554, 1147, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3875, 12, 2867, 389, 1600, 538, 291, 1345, 13, 203, 3639, 1071, 203, 3639, 353, 5541, 203, 3639, 622, 8755, 12, 31359, 18, 37, 4062, 31954, 13, 203, 565, 288, 203, 3639, 309, 261, 67, 1600, 538, 291, 1345, 422, 374, 13, 203, 5411, 604, 31, 203, 3639, 314, 18050, 291, 1345, 273, 3155, 24899, 1600, 538, 291, 1345, 1769, 203, 3639, 309, 261, 1600, 538, 291, 1345, 18, 12296, 951, 12, 2211, 13, 480, 4552, 67, 8412, 55, 67, 55, 11846, 13, 203, 5411, 604, 31, 203, 3639, 6009, 273, 934, 1023, 18, 37, 4062, 694, 1211, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xa88A48B7351d605F1116d81EebC2104A7f41253E/sources/contracts/interfaces/IOnChainMetadata.sol
@notice Storage for Lyrics
struct Lyrics { string lyrics; string lyricsNft; }
1,924,746
[ 1, 3245, 364, 511, 93, 1512, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 511, 93, 1512, 87, 288, 203, 3639, 533, 18519, 1512, 87, 31, 203, 3639, 533, 18519, 1512, 87, 50, 1222, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x41cB4a771FdD019ADBF4685bd4885fbBeedE1784/sources/contracts/EvilNoundlesVRF.sol
setCallbackSaleBlock + setOverrideCallbackSaleBlock + setWeaponsEnabled
function setSaleBlockandCSBandWep(uint256 _arg, bool _bool, bool _OCSB, bool _wep) public onlyOwner { callbackSaleBlock[_arg] = _bool; overrideCallbackSaleBlock = _OCSB; weaponsEnabled = _wep; }
3,121,487
[ 1, 542, 2428, 30746, 1768, 397, 444, 6618, 2428, 30746, 1768, 397, 444, 3218, 438, 7008, 1526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13928, 5349, 1768, 464, 4596, 14231, 59, 881, 12, 11890, 5034, 389, 3175, 16, 1426, 389, 6430, 16, 1426, 389, 51, 4596, 38, 16, 1426, 389, 91, 881, 13, 1071, 1338, 5541, 288, 203, 3639, 1348, 30746, 1768, 63, 67, 3175, 65, 282, 273, 389, 6430, 31, 203, 3639, 3849, 2428, 30746, 1768, 273, 389, 51, 4596, 38, 31, 203, 3639, 732, 438, 7008, 1526, 5411, 273, 389, 91, 881, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x78Dd414DF1fC487B5123314a17685D1dF34ff670/sources/project_/contracts/Fold.sol
* @notice mint the $Fold to the TWENTY contract upon NFT creation @param _amount amount to mint/
function mintStakingShare(uint _amount) external onlyOwner { uint256 realAmount = _amount*FOLD_TOKEN_PRECISION; if(realAmount + totalSupply() > MAX_SUPPLY){ revert("Tokens all allocated"); } _mint(address(foldStaking), realAmount); }
7,113,677
[ 1, 81, 474, 326, 271, 15592, 358, 326, 24722, 2222, 61, 6835, 12318, 423, 4464, 6710, 225, 389, 8949, 3844, 358, 312, 474, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 510, 6159, 9535, 12, 11890, 389, 8949, 13, 3903, 1338, 5541, 288, 203, 3639, 2254, 5034, 2863, 6275, 273, 389, 8949, 14, 42, 11846, 67, 8412, 67, 3670, 26913, 31, 203, 3639, 309, 12, 7688, 6275, 397, 2078, 3088, 1283, 1435, 405, 4552, 67, 13272, 23893, 15329, 203, 5411, 15226, 2932, 5157, 777, 11977, 8863, 203, 3639, 289, 203, 3639, 389, 81, 474, 12, 2867, 12, 16007, 510, 6159, 3631, 2863, 6275, 1769, 203, 565, 289, 203, 203, 377, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x66974a0DedAe6D50c57524F5eC8E5a02704e18D0/sources/contracts/LunacianScholarshipGuildToken.sol
* @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); _previousOwner = address(0); }
3,001,284
[ 1, 1682, 6606, 326, 6835, 2887, 3410, 18, 2597, 903, 486, 506, 3323, 358, 745, 1375, 3700, 5541, 68, 4186, 16828, 18, 4480, 1338, 506, 2566, 635, 326, 783, 3410, 18, 5219, 30, 25921, 465, 2822, 23178, 903, 8851, 326, 6835, 2887, 392, 3410, 16, 1915, 1637, 9427, 1281, 14176, 716, 353, 1338, 2319, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 1769, 203, 3639, 389, 11515, 5541, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; // library SafeMath { function ADD864(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB868(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB868(a, b, "SafeMath: subtraction overflow"); } function SUB868(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 MUL988(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 DIV926(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV926(a, b, "SafeMath: division by zero"); } function DIV926(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD713(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD713(a, b, "SafeMath: modulo by zero"); } function MOD713(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function SAFEAPPROVE567(address token, address to, uint value) internal { //inject NONSTANDARD NAMING // 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 SAFETRANSFER962(address token, address to, uint value) internal { //inject NONSTANDARD NAMING // 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 SAFETRANSFERFROM567(address token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING // 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 SAFETRANSFERETH46(address to, uint value) internal { //inject NONSTANDARD NAMING (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // library Math { function MAX98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN757(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE252(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // 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_entered371 = 1; //inject NONSTANDARD NAMING uint256 private constant _entered907 = 2; //inject NONSTANDARD NAMING uint256 private _status; constructor () internal { _status = _not_entered371; } modifier NONREENTRANT361() { //inject NONSTANDARD NAMING // On the first call to nonReentrant, _notEntered will be true require(_status != _entered907, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _entered907; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _not_entered371; } } // interface ICoFiXStakingRewards { // Views function REWARDSVAULT139() external view returns (address); //inject NONSTANDARD NAMING function LASTBLOCKREWARDAPPLICABLE573() external view returns (uint256); //inject NONSTANDARD NAMING function REWARDPERTOKEN122() external view returns (uint256); //inject NONSTANDARD NAMING function EARNED893(address account) external view returns (uint256); //inject NONSTANDARD NAMING function ACCRUED168() external view returns (uint256); //inject NONSTANDARD NAMING function REWARDRATE36() external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY567() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF980(address account) external view returns (uint256); //inject NONSTANDARD NAMING function STAKINGTOKEN641() external view returns (address); //inject NONSTANDARD NAMING function REWARDSTOKEN657() external view returns (address); //inject NONSTANDARD NAMING // Mutative function STAKE225(uint256 amount) external; //inject NONSTANDARD NAMING function STAKEFOROTHER357(address other, uint256 amount) external; //inject NONSTANDARD NAMING function WITHDRAW360(uint256 amount) external; //inject NONSTANDARD NAMING function EMERGENCYWITHDRAW536() external; //inject NONSTANDARD NAMING function GETREWARD438() external; //inject NONSTANDARD NAMING function GETREWARDANDSTAKE43() external; //inject NONSTANDARD NAMING function EXIT912() external; //inject NONSTANDARD NAMING function ADDREWARD881(uint256 amount) external; //inject NONSTANDARD NAMING // Events event REWARDADDED378(address sender, uint256 reward); //inject NONSTANDARD NAMING event STAKED268(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event STAKEDFOROTHER964(address indexed user, address indexed other, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAWN805(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW7(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event REWARDPAID501(address indexed user, uint256 reward); //inject NONSTANDARD NAMING } // interface ICoFiXVaultForLP { enum POOL_STATE {INVALID, ENABLED, DISABLED} event NEWPOOLADDED559(address pool, uint256 index); //inject NONSTANDARD NAMING event POOLENABLED434(address pool); //inject NONSTANDARD NAMING event POOLDISABLED539(address pool); //inject NONSTANDARD NAMING function SETGOVERNANCE394(address _new) external; //inject NONSTANDARD NAMING function SETINITCOFIRATE698(uint256 _new) external; //inject NONSTANDARD NAMING function SETDECAYPERIOD166(uint256 _new) external; //inject NONSTANDARD NAMING function SETDECAYRATE667(uint256 _new) external; //inject NONSTANDARD NAMING function ADDPOOL220(address pool) external; //inject NONSTANDARD NAMING function ENABLEPOOL504(address pool) external; //inject NONSTANDARD NAMING function DISABLEPOOL836(address pool) external; //inject NONSTANDARD NAMING function SETPOOLWEIGHT937(address pool, uint256 weight) external; //inject NONSTANDARD NAMING function BATCHSETPOOLWEIGHT100(address[] memory pools, uint256[] memory weights) external; //inject NONSTANDARD NAMING function DISTRIBUTEREWARD70(address to, uint256 amount) external; //inject NONSTANDARD NAMING function GETPENDINGREWARDOFLP590(address pair) external view returns (uint256); //inject NONSTANDARD NAMING function CURRENTPERIOD82() external view returns (uint256); //inject NONSTANDARD NAMING function CURRENTCOFIRATE163() external view returns (uint256); //inject NONSTANDARD NAMING function CURRENTPOOLRATE277(address pool) external view returns (uint256 poolRate); //inject NONSTANDARD NAMING function CURRENTPOOLRATEBYPAIR255(address pair) external view returns (uint256 poolRate); //inject NONSTANDARD NAMING function STAKINGPOOLFORPAIR714(address pair) external view returns (address pool); //inject NONSTANDARD NAMING function GETPOOLINFO427(address pool) external view returns (POOL_STATE state, uint256 weight); //inject NONSTANDARD NAMING function GETPOOLINFOBYPAIR166(address pair) external view returns (POOL_STATE state, uint256 weight); //inject NONSTANDARD NAMING function GETENABLEDPOOLCNT412() external view returns (uint256); //inject NONSTANDARD NAMING function GETCOFISTAKINGPOOL12() external view returns (address pool); //inject NONSTANDARD NAMING } // interface IERC20 { function TOTALSUPPLY567() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF980(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER204(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE758(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE960(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM982(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER211(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL330(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // interface ICoFiStakingRewards { // Views function REWARDPERTOKEN122() external view returns (uint256); //inject NONSTANDARD NAMING function EARNED893(address account) external view returns (uint256); //inject NONSTANDARD NAMING function ACCRUED168() external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY567() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF980(address account) external view returns (uint256); //inject NONSTANDARD NAMING function STAKINGTOKEN641() external view returns (address); //inject NONSTANDARD NAMING function REWARDSTOKEN657() external view returns (address); //inject NONSTANDARD NAMING // Mutative function STAKE225(uint256 amount) external; //inject NONSTANDARD NAMING function STAKEFOROTHER357(address other, uint256 amount) external; //inject NONSTANDARD NAMING function WITHDRAW360(uint256 amount) external; //inject NONSTANDARD NAMING function EMERGENCYWITHDRAW536() external; //inject NONSTANDARD NAMING function GETREWARD438() external; //inject NONSTANDARD NAMING function ADDETHREWARD660() external payable; //inject NONSTANDARD NAMING function EXIT912() external; //inject NONSTANDARD NAMING // Events event STAKED268(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event STAKEDFOROTHER964(address indexed user, address indexed other, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAWN805(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event SAVINGWITHDRAWN125(address indexed to, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW7(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event REWARDPAID501(address indexed user, uint256 reward); //inject NONSTANDARD NAMING } // interface ICoFiXFactory { // All pairs: {ETH <-> ERC20 Token} event PAIRCREATED889(address indexed token, address pair, uint256); //inject NONSTANDARD NAMING event NEWGOVERNANCE470(address _new); //inject NONSTANDARD NAMING event NEWCONTROLLER331(address _new); //inject NONSTANDARD NAMING event NEWFEERECEIVER222(address _new); //inject NONSTANDARD NAMING event NEWFEEVAULTFORLP508(address token, address feeVault); //inject NONSTANDARD NAMING event NEWVAULTFORLP769(address _new); //inject NONSTANDARD NAMING event NEWVAULTFORTRADER72(address _new); //inject NONSTANDARD NAMING event NEWVAULTFORCNODE372(address _new); //inject NONSTANDARD NAMING function CREATEPAIR976( //inject NONSTANDARD NAMING address token ) external returns (address pair); function GETPAIR599(address token) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS153(uint256) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH789() external view returns (uint256); //inject NONSTANDARD NAMING function GETTRADEMININGSTATUS473(address token) external view returns (bool status); //inject NONSTANDARD NAMING function SETTRADEMININGSTATUS493(address token, bool status) external; //inject NONSTANDARD NAMING function GETFEEVAULTFORLP473(address token) external view returns (address feeVault); // for LPs //inject NONSTANDARD NAMING function SETFEEVAULTFORLP669(address token, address feeVault) external; //inject NONSTANDARD NAMING function SETGOVERNANCE394(address _new) external; //inject NONSTANDARD NAMING function SETCONTROLLER726(address _new) external; //inject NONSTANDARD NAMING function SETFEERECEIVER908(address _new) external; //inject NONSTANDARD NAMING function SETVAULTFORLP99(address _new) external; //inject NONSTANDARD NAMING function SETVAULTFORTRADER40(address _new) external; //inject NONSTANDARD NAMING function SETVAULTFORCNODE20(address _new) external; //inject NONSTANDARD NAMING function GETCONTROLLER295() external view returns (address controller); //inject NONSTANDARD NAMING function GETFEERECEIVER766() external view returns (address feeReceiver); // For CoFi Holders //inject NONSTANDARD NAMING function GETVAULTFORLP604() external view returns (address vaultForLP); //inject NONSTANDARD NAMING function GETVAULTFORTRADER901() external view returns (address vaultForTrader); //inject NONSTANDARD NAMING function GETVAULTFORCNODE682() external view returns (address vaultForCNode); //inject NONSTANDARD NAMING } // // Stake XToken to earn CoFi Token contract CoFiXStakingRewards is ICoFiXStakingRewards, ReentrancyGuard { using SafeMath for uint256; address public override immutable rewardsToken; // CoFi address public override immutable stakingToken; // XToken or CNode address public immutable factory; uint256 public lastUpdateBlock; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; constructor( address _rewardsToken, address _stakingToken, address _factory ) public { rewardsToken = _rewardsToken; stakingToken = _stakingToken; require(ICoFiXFactory(_factory).GETVAULTFORLP604() != address(0), "VaultForLP not set yet"); // check factory = _factory; lastUpdateBlock = 11040688; // https://etherscan.io/block/countdown/11040688 } // replace cofixVault with rewardsVault, this could introduce more calls, but clear is more important function REWARDSVAULT139() public virtual override view returns (address) { //inject NONSTANDARD NAMING return ICoFiXFactory(factory).GETVAULTFORLP604(); } function TOTALSUPPLY567() external override view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF980(address account) external override view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function LASTBLOCKREWARDAPPLICABLE573() public override view returns (uint256) { //inject NONSTANDARD NAMING return block.number; } function REWARDPERTOKEN122() public override view returns (uint256) { //inject NONSTANDARD NAMING if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.ADD864( ACCRUED168().MUL988(1e18).DIV926(_totalSupply) ); } function _REWARDPERTOKENANDACCRUED426() internal view returns (uint256, uint256) { //inject NONSTANDARD NAMING if (_totalSupply == 0) { // use the old rewardPerTokenStored, and accrued should be zero here // if not the new accrued amount will never be distributed to anyone return (rewardPerTokenStored, 0); } uint256 _accrued = ACCRUED168(); uint256 _rewardPerToken = rewardPerTokenStored.ADD864( _accrued.MUL988(1e18).DIV926(_totalSupply) ); return (_rewardPerToken, _accrued); } function REWARDRATE36() public virtual override view returns (uint256) { //inject NONSTANDARD NAMING return ICoFiXVaultForLP(REWARDSVAULT139()).CURRENTPOOLRATE277(address(this)); } function ACCRUED168() public virtual override view returns (uint256) { //inject NONSTANDARD NAMING // calc block rewards uint256 blockReward = LASTBLOCKREWARDAPPLICABLE573().SUB868(lastUpdateBlock).MUL988(REWARDRATE36()); // query pair trading rewards uint256 tradingReward = ICoFiXVaultForLP(REWARDSVAULT139()).GETPENDINGREWARDOFLP590(stakingToken); return blockReward.ADD864(tradingReward); } function EARNED893(address account) public override view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account].MUL988(REWARDPERTOKEN122().SUB868(userRewardPerTokenPaid[account])).DIV926(1e18).ADD864(rewards[account]); } function STAKE225(uint256 amount) external override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.ADD864(amount); _balances[msg.sender] = _balances[msg.sender].ADD864(amount); TransferHelper.SAFETRANSFERFROM567(stakingToken, msg.sender, address(this), amount); emit STAKED268(msg.sender, amount); } function STAKEFOROTHER357(address other, uint256 amount) external override NONREENTRANT361 UPDATEREWARD178(other) { //inject NONSTANDARD NAMING require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.ADD864(amount); _balances[other] = _balances[other].ADD864(amount); TransferHelper.SAFETRANSFERFROM567(stakingToken, msg.sender, address(this), amount); emit STAKEDFOROTHER964(msg.sender, other, amount); } function WITHDRAW360(uint256 amount) public override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.SUB868(amount); _balances[msg.sender] = _balances[msg.sender].SUB868(amount); TransferHelper.SAFETRANSFER962(stakingToken, msg.sender, amount); emit WITHDRAWN805(msg.sender, amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function EMERGENCYWITHDRAW536() external override NONREENTRANT361 { //inject NONSTANDARD NAMING uint256 amount = _balances[msg.sender]; require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.SUB868(amount); _balances[msg.sender] = 0; rewards[msg.sender] = 0; TransferHelper.SAFETRANSFER962(stakingToken, msg.sender, amount); emit EMERGENCYWITHDRAW7(msg.sender, amount); } function GETREWARD438() public override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; // TransferHelper.safeTransfer(rewardsToken, msg.sender, reward); uint256 transferred = _SAFECOFITRANSFER191(msg.sender, reward); emit REWARDPAID501(msg.sender, transferred); } } // get CoFi rewards and staking into CoFiStakingRewards pool function GETREWARDANDSTAKE43() external override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; address cofiStakingPool = ICoFiXVaultForLP(REWARDSVAULT139()).GETCOFISTAKINGPOOL12(); // also work for VaultForCNode require(cofiStakingPool != address(0), "cofiStakingPool not set"); // approve to staking pool address _rewardsToken = rewardsToken; IERC20(_rewardsToken).APPROVE960(cofiStakingPool, reward); ICoFiStakingRewards(cofiStakingPool).STAKEFOROTHER357(msg.sender, reward); IERC20(_rewardsToken).APPROVE960(cofiStakingPool, 0); // ensure emit REWARDPAID501(msg.sender, reward); } } function EXIT912() external override { //inject NONSTANDARD NAMING WITHDRAW360(_balances[msg.sender]); GETREWARD438(); } // add reward from trading pool or anyone else function ADDREWARD881(uint256 amount) public override NONREENTRANT361 UPDATEREWARD178(address(0)) { //inject NONSTANDARD NAMING // transfer from caller (router contract) TransferHelper.SAFETRANSFERFROM567(rewardsToken, msg.sender, address(this), amount); // update rewardPerTokenStored rewardPerTokenStored = rewardPerTokenStored.ADD864(amount.MUL988(1e18).DIV926(_totalSupply)); emit REWARDADDED378(msg.sender, amount); } // Safe CoFi transfer function, just in case if rounding error or ending of mining causes pool to not have enough CoFis. function _SAFECOFITRANSFER191(address _to, uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING uint256 cofiBal = IERC20(rewardsToken).BALANCEOF980(address(this)); if (_amount > cofiBal) { _amount = cofiBal; } TransferHelper.SAFETRANSFER962(rewardsToken, _to, _amount); // allow zero amount return _amount; } modifier UPDATEREWARD178(address account) virtual { //inject NONSTANDARD NAMING // rewardPerTokenStored = rewardPerToken(); // uint256 newAccrued = accrued(); (uint256 newRewardPerToken, uint256 newAccrued) = _REWARDPERTOKENANDACCRUED426(); rewardPerTokenStored = newRewardPerToken; if (newAccrued > 0) { // distributeReward could fail if CoFiXVaultForLP is not minter of CoFi anymore // Should set reward rate to zero first, and then do a settlement of pool reward by call getReward ICoFiXVaultForLP(REWARDSVAULT139()).DISTRIBUTEREWARD70(address(this), newAccrued); } lastUpdateBlock = LASTBLOCKREWARDAPPLICABLE573(); if (account != address(0)) { rewards[account] = EARNED893(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } event REWARDADDED378(address sender, uint256 reward); //inject NONSTANDARD NAMING event STAKED268(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event STAKEDFOROTHER964(address indexed user, address indexed other, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAWN805(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW7(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event REWARDPAID501(address indexed user, uint256 reward); //inject NONSTANDARD NAMING }
inject NONSTANDARD NAMING
function ALLPAIRS153(uint256) external view returns (address pair);
1,840,778
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8061, 4066, 7937, 55, 30305, 12, 11890, 5034, 13, 3903, 1476, 1135, 261, 2867, 3082, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Unlicense pragma solidity ^0.7.0; //Order struct struct Order { bytes32 id; address token_address; uint256 block_nr; bool order_type; address sender; uint256 eth_sent; uint256 eth_left; uint256 token_amount; uint256 token_left; uint256 limit; bool executed; bool cancelled; bytes32 previous_order; bytes32 next_order; } //Trade struct struct Trade { bytes32 id; address token_address; uint256 block_nr; uint256 timestamp; bool order_type; bytes32 buy_order_id; bytes32 sell_order_id; uint256 exec_amount; uint256 price; } //Exchange Struct struct Exchange { //First order of the queue mapping(address => bytes32) first_buy_order_id; mapping(address => bytes32) first_sell_order_id; //mapping of all orders by order_id in uint format //can be reconverted to the right format using web3.toHex mapping(address => mapping(bytes32 => Order)) orders; mapping(address => uint256[]) order_list; //Executions records //(i) mapping token => execution_id => execution //(ii) mapping token => (uint) execution_id mapping(address => mapping(bytes32 => Trade)) trades; mapping(address => uint256[]) trade_list; //mapping of address with current balance with the exchange mapping(address => uint256) eth_balance; mapping(address => mapping(address => uint256)) token_balance; //mapping of listed tokens mapping(address => string) listed_tokens; mapping(address => bool) is_token_listed; address[] token_list_array; bool is_exchange_open; } contract _0xChange { Exchange public exchange; constructor(){ exchange.is_exchange_open = true; } function buy(address _token, uint _amount, uint _limit) public payable { _0xChangeLib.place_buy_order(exchange, _token, _amount, _limit); } function sell(address _seller, address _token, uint _amount, uint _limit) public { _0xChangeLib.place_sell_order(exchange, _seller, _token, _amount, _limit); } function takeEth() public { _0xChangeLib.withdrawEth(exchange); } function takeCoin(address _token) public { _0xChangeLib.withdrawToken(exchange, _token); } function cancel(address _token, bytes32 orderId) public { _0xChangeLib.cancelOrder(exchange, _token, orderId); } function receiveApproval(address _from, uint _token, address _tokenContract, bytes memory _data) public { if(!ERC20Interface(_tokenContract).transferFrom(_from, address(this), _token)) { revert(); } _0xChangeLib.place_sell_order(exchange, _from, _tokenContract, _token, toUint256(_data)); } // ------------------------------------------------------------------------ // Getters and setters for web3 interface // ------------------------------------------------------------------------ // User function getEthBalance(address user) public view returns(uint256) { return exchange.eth_balance[user]; } function getTokenBalance(address token, address user) public view returns(uint256) { return exchange.token_balance[token][user]; } // Tokens function getTokenListLength() public view returns(uint) { return exchange.token_list_array.length; } function getTokenAddress(uint pos) public view returns(address) { return exchange.token_list_array[pos]; } function getTokenSymbol(address tokenAddress) public view returns(string memory) { return exchange.listed_tokens[tokenAddress]; } function addToken(address tokenAddress) public { if(exchange.is_token_listed[tokenAddress] == false) { exchange.token_list_array.push(tokenAddress); exchange.listed_tokens[tokenAddress] = ERC20Interface(tokenAddress).symbol(); exchange.is_token_listed[tokenAddress] = true; } else { exchange.listed_tokens[tokenAddress] = ERC20Interface(tokenAddress).symbol(); } } //Info function getLastPrice(address tokenAddress) public view returns(uint) { return exchange.trades[tokenAddress][bytes32(exchange.trade_list[tokenAddress][getExecutionsLength(tokenAddress)-1])].price; } function getFirstBuyOrder(address tokenAddress) public view returns(bytes32) { return exchange.first_buy_order_id[tokenAddress]; } function getFirstSellOrder(address tokenAddress) public view returns(bytes32) { return exchange.first_sell_order_id[tokenAddress]; } function getOrderLimit(address tokenAddress, bytes32 id) public view returns(uint256) { return exchange.orders[tokenAddress][id].limit; } function getOrderEthLeft(address tokenAddress, bytes32 id) public view returns(uint256) { return exchange.orders[tokenAddress][id].eth_left; } function getOrderTokenLeft(address tokenAddress, bytes32 id) public view returns(uint256) { return exchange.orders[tokenAddress][id].token_left; } // Executions function getExecutionsLength(address _token) public view returns(uint) { return exchange.trade_list[_token].length; } function toUint256(bytes memory _b) public pure returns(uint256 value) { assembly { value := mload(add(_b, 0x20)) } } } library _0xChangeLib { //Event generated when an order is placed successfully event Placed(bytes32 order_id, address token_address, uint block_nr, bool order_type, address sender, uint eth_left, uint token_left, uint limit, bool executed, bool cancelled, bytes32 previous_order, bytes32 next_order); event Updated(bytes32 order_id, address token, uint eth_left, uint token_left, bool executed, bool cancelled, bytes32 previous_order, bytes32 next_order); event Traded(bytes32 trade_id, address token_address, uint block_nr, uint trade_timestamp, bool order_type, bytes32 buy_order_id, bytes32 sell_order_id, uint trade_amount, uint trade_price); // ------------------------------------------------------------------------ // Place an order in the orders mapping // The chain is organized with market order first and then // Limit order sorted from highest to lowest bid // ------------------------------------------------------------------------ function place_buy_order(Exchange storage self, address _token, uint _amount, uint _limit) public returns (bool success) { require(_amount * _limit / (10**uint(getDecimals(_token))) <= msg.value); require(msg.value > 0); require(self.is_exchange_open); bytes32 order_id = keccak256( abi.encodePacked( block.number, _token, msg.sender, _amount, _limit)); Order memory myOrder = Order({ id: order_id, token_address: _token, block_nr: block.number, order_type: true, sender: msg.sender, eth_sent: msg.value, eth_left: msg.value, token_amount: _amount, token_left: _amount, limit: _limit, executed: false, cancelled: false, previous_order: bytes32(0), next_order: bytes32(0) }); self.orders[_token][order_id] = myOrder; insertBuyOrder(self, _token, order_id); emitOrder(self, _token, order_id); matching(self, _token, true); return true; } // ------------------------------------------------------------------------ // Place an order in the orders mapping // Called internally from ReceiveApproval // The chain is organized with market order first and then // Limit order sorted from high lowest to highes ask // ------------------------------------------------------------------------ function place_sell_order(Exchange storage self, address _seller, address _token, uint _amount, uint _limit) internal returns (bool success) { require(self.is_exchange_open); bytes32 order_id = keccak256( abi.encodePacked( block.number, _token, msg.sender, _amount, _limit)); Order memory myOrder = Order({ id: order_id, token_address: _token, block_nr: block.number, order_type: false, sender: _seller, eth_sent: 0, eth_left: 0, token_amount: _amount, token_left: _amount, limit: _limit, executed: false, cancelled: false, previous_order: bytes32(0), next_order: bytes32(0) }); self.orders[_token][order_id] = myOrder; insertSellOrder(self, _token, order_id); emitOrder(self,_token, order_id); matching(self, _token, false); return true; } // ------------------------------------------------------------------------ // Insert a buy order in the order queue // Market orders are placed first sorted by seniority // Limit orders are placed with highest bid first and then sorted // by seniority // ------------------------------------------------------------------------ function insertBuyOrder(Exchange storage self, address _token, bytes32 _order_id) internal { bytes32 position; //In case no other buy order exists if(self.first_buy_order_id[_token] == 0) { self.first_buy_order_id[_token] = _order_id; return; } //loop through the buy order book and insert new buy orders position = self.first_buy_order_id[_token]; do { //insert market orders before limit order (first market order) if(self.orders[_token][_order_id].limit == 0 && self.orders[_token][position].limit != 0 && (self.orders[_token][getPreviousOrder(self, _token, position)].id == 0 || self.orders[_token][getPreviousOrder(self, _token, position)].limit == 0)) { if(self.orders[_token][getPreviousOrder(self, _token, position)].id == 0) self.first_buy_order_id[_token] = _order_id; self.orders[_token][_order_id].previous_order = getPreviousOrder(self, _token, position); self.orders[_token][_order_id].next_order = position; self.orders[_token][getPreviousOrder(self, _token, position)].next_order = _order_id; self.orders[_token][position].previous_order = _order_id; return; } //insert market order after the last market order if(self.orders[_token][_order_id].limit == 0 && self.orders[_token][position].limit == 0 && (self.orders[_token][getNextOrder(self, _token, position)].id == 0 || self.orders[_token][getNextOrder(self, _token, position)].limit != 0)) { self.orders[_token][_order_id].previous_order = position; self.orders[_token][_order_id].next_order = self.orders[_token][position].next_order; self.orders[_token][getNextOrder(self, _token, position)].previous_order = _order_id; self.orders[_token][position].next_order = _order_id; return; } //insert limit order for new highest bid if(self.orders[_token][_order_id].limit != 0 && self.orders[_token][position].limit != 0 && self.orders[_token][_order_id].limit > self.orders[_token][position].limit && (self.orders[_token][getPreviousOrder(self, _token, position)].id == 0 || self.orders[_token][getPreviousOrder(self, _token, position)].limit == 0)) { if(self.orders[_token][getPreviousOrder(self, _token, position)].id == 0) self.first_buy_order_id[_token] = _order_id; self.orders[_token][_order_id].previous_order = self.orders[_token][getPreviousOrder(self, _token, position)].id; self.orders[_token][_order_id].next_order = position; self.orders[_token][getPreviousOrder(self, _token, position)].next_order = _order_id; self.orders[_token][position].previous_order = _order_id; return; } //insert limit order, case where the order is among existing limit buy orders //or first limit order after market order(s) if((self.orders[_token][_order_id].limit != 0 && self.orders[_token][position].limit != 0 && self.orders[_token][_order_id].limit <= self.orders[_token][position].limit && self.orders[_token][_order_id].block_nr >= self.orders[_token][position].block_nr && (self.orders[_token][getNextOrder(self, _token, position)].id == 0 || self.orders[_token][_order_id].limit > self.orders[_token][getNextOrder(self, _token, position)].limit)) || self.orders[_token][_order_id].limit != 0 && self.orders[_token][position].limit == 0 && self.orders[_token][getNextOrder(self, _token, position)].id == 0) { self.orders[_token][_order_id].previous_order = position; self.orders[_token][_order_id].next_order = getNextOrder(self, _token, position); self.orders[_token][getNextOrder(self, _token, position)].previous_order = _order_id; self.orders[_token][position].next_order = _order_id; return; } position = getNextOrder(self, _token, position); } while(position != 0); } // ------------------------------------------------------------------------ // Insert a sell order in the order queue // Market orders are placed first sorted by seniority // Limit orders are placed with lowest ask first and then sorted // by seniority // ------------------------------------------------------------------------ function insertSellOrder(Exchange storage self, address _token, bytes32 _order_id) internal { bytes32 position; if(self.first_sell_order_id[_token] == 0) { self.first_sell_order_id[_token] = _order_id; return; } position = self.first_sell_order_id[_token]; do { //insert orders, market orders with limit 0 first_sell_order_id //then limit order by ascending order. Orders of equal limit //sorted ascending by block nr if(self.orders[_token][_order_id].limit < self.orders[_token][position].limit) { if(self.orders[_token][position].previous_order == 0) { self.first_sell_order_id[_token] = _order_id; } self.orders[_token][_order_id].previous_order = getPreviousOrder(self, _token, position); self.orders[_token][_order_id].next_order = position; self.orders[_token][getPreviousOrder(self, _token, position)].next_order = _order_id; self.orders[_token][position].previous_order = _order_id; return; } //insert limit order, case where the order is among existing limit buy orders if(self.orders[_token][_order_id].limit >= self.orders[_token][position].limit && (self.orders[_token][_order_id].limit < self.orders[_token][getNextOrder(self, _token, position)].limit || self.orders[_token][getNextOrder(self, _token, position)].id == 0) && self.orders[_token][_order_id].block_nr >= self.orders[_token][position].block_nr) { self.orders[_token][_order_id].previous_order = position; self.orders[_token][_order_id].next_order = getNextOrder(self, _token, position); self.orders[_token][getNextOrder(self, _token, position)].previous_order = _order_id; self.orders[_token][position].next_order = _order_id; return; } position = getNextOrder(self, _token, position); } while(position != 0); } // ------------------------------------------------------------------------ // Cancel an order, remove it from the chain of orders and // increase eth balance of the trader by the eth left and token left // ------------------------------------------------------------------------ function cancelOrder(Exchange storage self, address _token, bytes32 orderId) public { require(msg.sender == self.orders[_token][orderId].sender); require(self.orders[_token][orderId].cancelled == false); require(self.orders[_token][orderId].executed == false); Order memory _order = self.orders[_token][orderId]; if(_order.order_type == true) { if(self.first_buy_order_id[_token] == orderId){ self.first_buy_order_id[_token] = _order.next_order; self.orders[_token][_order.next_order].previous_order = _order.previous_order; self.eth_balance[_order.sender] += _order.eth_left; } else { self.orders[_token][_order.previous_order].next_order = _order.next_order; self.orders[_token][_order.next_order].previous_order = _order.previous_order; self.eth_balance[_order.sender] += _order.eth_left; } } else { if(self.first_sell_order_id[_token] == orderId){ self.first_sell_order_id[_token] = _order.next_order; self.orders[_token][_order.next_order].previous_order = _order.previous_order; self.token_balance[_token][_order.sender] += _order.token_left; } else { self.orders[_token][_order.previous_order].next_order = _order.next_order; self.orders[_token][_order.next_order].previous_order = _order.previous_order; self.token_balance[_token][_order.sender] += _order.token_left; } } _order.previous_order = bytes32(0); _order.next_order = bytes32(0); _order.cancelled = true; _order.eth_left = 0; _order.token_left = 0; self.orders[_token][orderId] = _order; updateOrder(self, _token, orderId); } // ------------------------------------------------------------------------ // Withdraw Eth from the traders balance // ------------------------------------------------------------------------ function withdrawEth(Exchange storage self) public { uint balance = self.eth_balance[msg.sender]; self.eth_balance[msg.sender] = 0; msg.sender.transfer(balance); } // ------------------------------------------------------------------------ // Withdraw Tokens from the traders balance // ------------------------------------------------------------------------ function withdrawToken(Exchange storage self, address _token) public { uint balance = self.token_balance[_token][msg.sender]; self.token_balance[_token][msg.sender] = 0; ERC20Interface(_token).transfer(msg.sender, balance); } // ------------------------------------------------------------------------ // Match orders in the book // 1) Market orders are matched together using the lower of // the last paid price on the exchange and the lowest ask // 2) Limit orders are matched together until bid < ask // ------------------------------------------------------------------------ function matching(Exchange storage self, address _token, bool _type) public { bytes32 exec_id; uint price; uint amount; while (isMatchingPossible(self, _token)) { //set execution price for market vs market, //market vs limit order, limit vs market //and limit vs. limit type of order price = transactionPrice(self, _token, _type); amount = transactionAmount(self, _token, price); exec_id = keccak256( abi.encodePacked( _token, block.number, _token, self.first_buy_order_id[_token], self.first_sell_order_id[_token], amount, price)); self.trade_list[_token].push(uint256(exec_id)); //Settle payment and finalize the trade settlement(self, _token, amount, price, self.orders[_token][self.first_buy_order_id[_token]].sender, self.orders[_token][self.first_sell_order_id[_token]].sender); //Emit trade confirmation emit Traded(exec_id, _token, block.number, block.timestamp, _type, self.first_buy_order_id[_token], self.first_sell_order_id[_token], amount, price); } } // ------------------------------------------------------------------------ // Arrange the settlement by: // 1) reducing the buy and sell order amounts by the transaction amount // 2) push the execution ID in the execution array of the orders // 3) increase the token balance of the buyer and the eth balance of // the seller, book the fees and emit the Execution event // 4) close orders that have been executed, buy amount considered executed // once remaining ETH is smaller than 10000000000 gwei. // ------------------------------------------------------------------------ function settlement(Exchange storage self, address _token, uint amount, uint price, address buyer, address seller) internal { uint trx_volume = amount * price / (10**uint(getDecimals(_token))); bytes32 tempOrder; //update orders self.orders[_token][self.first_buy_order_id[_token]].token_left -= amount; self.orders[_token][self.first_sell_order_id[_token]].token_left -= amount; self.orders[_token][self.first_buy_order_id[_token]].eth_left -= trx_volume; //Emit Updated on the buy order updateOrder(self, _token, self.first_buy_order_id[_token]); updateOrder(self, _token, self.first_sell_order_id[_token]); //Consider an order as executed if the token amount left is zero //or if the eth amount left is smaller than 1000000000 wei (0.00000001 ETH) if(self.orders[_token][self.first_buy_order_id[_token]].token_left == 0 || self.orders[_token][self.first_buy_order_id[_token]].eth_left < 1000000000) { self.orders[_token][self.first_buy_order_id[_token]].executed = true; self.eth_balance[buyer] += self.orders[_token][self.first_buy_order_id[_token]].eth_left; self.eth_balance[buyer] += self.orders[_token][self.first_buy_order_id[_token]].eth_left; self.orders[_token][self.first_buy_order_id[_token]].eth_left = 0; tempOrder = self.orders[_token][self.first_buy_order_id[_token]].next_order; self.orders[_token][self.first_buy_order_id[_token]].previous_order = bytes32(0); self.orders[_token][self.first_buy_order_id[_token]].next_order = bytes32(0); //update old first buy order updateOrder(self, _token, self.first_buy_order_id[_token]); self.first_buy_order_id[_token] = tempOrder; self.orders[_token][self.first_buy_order_id[_token]].previous_order = bytes32(0); //update new first buy order updateOrder(self, _token, self.first_buy_order_id[_token]); } if(self.orders[_token][self.first_sell_order_id[_token]].token_left == 0) { self.orders[_token][self.first_sell_order_id[_token]].executed = true; tempOrder = self.orders[_token][self.first_sell_order_id[_token]].next_order; self.orders[_token][self.first_sell_order_id[_token]].previous_order = bytes32(0); self.orders[_token][self.first_sell_order_id[_token]].next_order = bytes32(0); //update old first sell order updateOrder(self, _token, self.first_sell_order_id[_token]); self.first_sell_order_id[_token] = tempOrder; self.orders[_token][self.first_sell_order_id[_token]].previous_order = bytes32(0); //update new first sell order updateOrder(self, _token, self.first_sell_order_id[_token]); } } // ------------------------------------------------------------------------ // Compare the first orders of the bid and ask and define if // a matching is possible // ------------------------------------------------------------------------ function isMatchingPossible(Exchange storage self, address _token) internal view returns (bool) { return (self.orders[_token][self.first_buy_order_id[_token]].limit >= self.orders[_token][self.first_sell_order_id[_token]].limit || (self.orders[_token][self.first_buy_order_id[_token]].limit == 0 || self.orders[_token][self.first_sell_order_id[_token]].limit == 0)) && (self.first_buy_order_id[_token] != 0 && self.first_sell_order_id[_token] != 0); } // ------------------------------------------------------------------------ // Return the transaction price: // 1) Market order vs Market order: lower of last price or best offer // 2) Market order vs Limit Order: limit order // ------------------------------------------------------------------------ function transactionPrice(Exchange storage self, address _token, bool _type) internal view returns (uint) { //Market order against market order //We call the getBestPrice function, which returns the lowest of //the last trade or the best bid if(self.orders[_token][self.first_buy_order_id[_token]].limit == 0 && self.orders[_token][self.first_sell_order_id[_token]].limit == 0) { return getBestPrice(self, _token); //Buy order at best vs limited sell order ==> ask price } else if(self.orders[_token][self.first_buy_order_id[_token]].limit == 0 && self.orders[_token][self.first_sell_order_id[_token]].limit != 0) { return self.orders[_token][self.first_sell_order_id[_token]].limit; //Limited buy order vs market sell order ==> bid price } else if(self.orders[_token][self.first_buy_order_id[_token]].limit != 0 && self.orders[_token][self.first_sell_order_id[_token]].limit == 0) { return self.orders[_token][self.first_buy_order_id[_token]].limit; //Limited buy order vs limited sell order // ==> limit placed by the counterparty not initiating the trade } else if (self.orders[_token][self.first_buy_order_id[_token]].limit != 0 && self.orders[_token][self.first_sell_order_id[_token]].limit != 0) { if(_type) return self.orders[_token][self.first_sell_order_id[_token]].limit; else return self.orders[_token][self.first_buy_order_id[_token]].limit; } } // ------------------------------------------------------------------------ // Return transaction amount as the lowest of the bid amount, // the offer amount and the maximal amount that the buyers can aquire as // the ether left on the order divided by the transaction price // ------------------------------------------------------------------------ function transactionAmount(Exchange storage self, address _token, uint price) internal view returns(uint) { return min(self.orders[_token][self.first_buy_order_id[_token]].token_left, min( self.orders[_token][self.first_buy_order_id[_token]].eth_left * (10**uint(ERC20Interface(_token).decimals())) / price, self.orders[_token][self.first_sell_order_id[_token]].token_left)); } // ------------------------------------------------------------------------ // Calculate best price for market orders by returning // the lower of the the last price paid or the lowest ask // ------------------------------------------------------------------------ function getBestPrice(Exchange storage self, address _token) public view returns (uint price) { //lowest of last paid price or lowest limit sell order //used to execute market orders bytes32 position = self.first_sell_order_id[_token]; uint best_price = getLastPrice(self, _token); while(self.orders[_token][position].id != 0) { if(self.orders[_token][position].limit != 0) { if(self.orders[_token][position].limit < best_price) { best_price = self.orders[_token][position].limit; } return best_price; } position = self.orders[_token][getNextOrder(self, _token, position)].id; } } // ------------------------------------------------------------------------ // Emit function places separately for conciseness // ------------------------------------------------------------------------ function emitOrder(Exchange storage self, address token, bytes32 order_id) internal { emit Placed( order_id, token, self.orders[token][order_id].block_nr, self.orders[token][order_id].order_type, self.orders[token][order_id].sender, self.orders[token][order_id].eth_left, self.orders[token][order_id].token_left, self.orders[token][order_id].limit, self.orders[token][order_id].executed, self.orders[token][order_id].cancelled, self.orders[token][order_id].previous_order, self.orders[token][order_id].next_order); } function updateOrder(Exchange storage self, address token, bytes32 order_id) internal { emit Updated( order_id, token, self.orders[token][order_id].eth_left, self.orders[token][order_id].token_left, self.orders[token][order_id].executed, self.orders[token][order_id].cancelled, self.orders[token][order_id].previous_order, self.orders[token][order_id].next_order); } //Orders function getPreviousOrder(Exchange storage self, address _token, bytes32 _orderId) public view returns (bytes32) { return self.orders[_token][_orderId].previous_order; } function getNextOrder(Exchange storage self, address _token, bytes32 _orderId) public view returns (bytes32) { return self.orders[_token][_orderId].next_order; } function getLastPrice(Exchange storage self, address tokenAddress) public view returns (uint256) { return self.trades[tokenAddress][bytes32(self.trade_list[tokenAddress][getExecutionsLength(self, tokenAddress) - 1])].price; } // Order function getOrderFrom(Exchange storage self, address _token, bytes32 _orderId) public view returns (address) { return self.orders[_token][_orderId].sender; } function getExecutionsLength(Exchange storage self, address _token) public view returns (uint256) { return self.trade_list[_token].length; } //Info function getDecimals(address tokenAddress) public view returns(uint) { return ERC20Interface(tokenAddress).decimals(); } // Various utils function max(uint a, uint b) internal pure returns (uint) { if(a >= b) return a; else return b; } function min(uint a, uint b) internal pure returns (uint) { if(a <= b) return a; else return b; } } //ERC20Interface abstract contract ERC20Interface { uint8 public decimals; string public symbol; string public name; function totalSupply() public virtual returns (uint256); function balanceOf(address tokenOwner) public virtual returns (uint256 balance); function allowance(address tokenOwner, address spender) public virtual returns (uint256 remaining); function transfer(address to, uint256 tokens) public virtual returns (bool success); function approve(address spender, uint256 tokens) public virtual returns (bool success); function transferFrom( address from, address to, uint256 tokens ) public virtual returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval( address indexed tokenOwner, address indexed spender, uint256 tokens ); }
update ordersEmit Updated on the buy orderConsider an order as executed if the token amount left is zeroor if the eth amount left is smaller than 1000000000 wei (0.00000001 ETH)update old first buy orderupdate new first buy orderupdate old first sell orderupdate new first sell order
function settlement(Exchange storage self, address _token, uint amount, uint price, address buyer, address seller) internal { uint trx_volume = amount * price / (10**uint(getDecimals(_token))); bytes32 tempOrder; self.orders[_token][self.first_buy_order_id[_token]].token_left -= amount; self.orders[_token][self.first_sell_order_id[_token]].token_left -= amount; self.orders[_token][self.first_buy_order_id[_token]].eth_left -= trx_volume; updateOrder(self, _token, self.first_buy_order_id[_token]); updateOrder(self, _token, self.first_sell_order_id[_token]); if(self.orders[_token][self.first_buy_order_id[_token]].token_left == 0 || self.orders[_token][self.first_buy_order_id[_token]].eth_left < 1000000000) { self.orders[_token][self.first_buy_order_id[_token]].executed = true; self.eth_balance[buyer] += self.orders[_token][self.first_buy_order_id[_token]].eth_left; self.eth_balance[buyer] += self.orders[_token][self.first_buy_order_id[_token]].eth_left; self.orders[_token][self.first_buy_order_id[_token]].eth_left = 0; tempOrder = self.orders[_token][self.first_buy_order_id[_token]].next_order; self.orders[_token][self.first_buy_order_id[_token]].previous_order = bytes32(0); self.orders[_token][self.first_buy_order_id[_token]].next_order = bytes32(0); updateOrder(self, _token, self.first_buy_order_id[_token]); self.first_buy_order_id[_token] = tempOrder; self.orders[_token][self.first_buy_order_id[_token]].previous_order = bytes32(0); updateOrder(self, _token, self.first_buy_order_id[_token]); } if(self.orders[_token][self.first_sell_order_id[_token]].token_left == 0) { self.orders[_token][self.first_sell_order_id[_token]].executed = true; tempOrder = self.orders[_token][self.first_sell_order_id[_token]].next_order; self.orders[_token][self.first_sell_order_id[_token]].previous_order = bytes32(0); self.orders[_token][self.first_sell_order_id[_token]].next_order = bytes32(0); updateOrder(self, _token, self.first_sell_order_id[_token]); self.first_sell_order_id[_token] = tempOrder; self.orders[_token][self.first_sell_order_id[_token]].previous_order = bytes32(0); updateOrder(self, _token, self.first_sell_order_id[_token]); } }
5,352,809
[ 1, 2725, 11077, 17982, 19301, 603, 326, 225, 30143, 1353, 9054, 3585, 392, 1353, 487, 7120, 309, 326, 1147, 3844, 2002, 353, 3634, 280, 309, 326, 13750, 3844, 2002, 353, 10648, 2353, 15088, 3784, 732, 77, 261, 20, 18, 9449, 1611, 512, 2455, 13, 2725, 1592, 1122, 30143, 1353, 2725, 394, 1122, 30143, 1353, 2725, 1592, 1122, 357, 80, 1353, 2725, 394, 1122, 357, 80, 1353, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 26319, 806, 12, 11688, 2502, 365, 16, 1758, 389, 2316, 16, 2254, 3844, 16, 2254, 6205, 16, 7010, 3639, 1758, 27037, 16, 1758, 29804, 13, 2713, 288, 203, 203, 3639, 2254, 433, 92, 67, 9491, 273, 3844, 380, 6205, 342, 261, 2163, 636, 11890, 12, 588, 31809, 24899, 2316, 3719, 1769, 203, 3639, 1731, 1578, 1906, 2448, 31, 203, 203, 3639, 365, 18, 9972, 63, 67, 2316, 6362, 2890, 18, 3645, 67, 70, 9835, 67, 1019, 67, 350, 63, 67, 2316, 65, 8009, 2316, 67, 4482, 3947, 3844, 31, 203, 3639, 365, 18, 9972, 63, 67, 2316, 6362, 2890, 18, 3645, 67, 87, 1165, 67, 1019, 67, 350, 63, 67, 2316, 65, 8009, 2316, 67, 4482, 3947, 3844, 31, 203, 3639, 365, 18, 9972, 63, 67, 2316, 6362, 2890, 18, 3645, 67, 70, 9835, 67, 1019, 67, 350, 63, 67, 2316, 65, 8009, 546, 67, 4482, 3947, 433, 92, 67, 9491, 31, 203, 203, 3639, 1089, 2448, 12, 2890, 16, 389, 2316, 16, 365, 18, 3645, 67, 70, 9835, 67, 1019, 67, 350, 63, 67, 2316, 19226, 203, 3639, 1089, 2448, 12, 2890, 16, 389, 2316, 16, 365, 18, 3645, 67, 87, 1165, 67, 1019, 67, 350, 63, 67, 2316, 19226, 203, 7010, 3639, 309, 12, 2890, 18, 9972, 63, 67, 2316, 6362, 2890, 18, 3645, 67, 70, 9835, 67, 1019, 67, 350, 63, 67, 2316, 65, 8009, 2316, 67, 4482, 422, 374, 747, 203, 5411, 365, 18, 9972, 63, 67, 2316, 6362, 2890, 18, 3645, 67, 70, 9835, 67, 1019, 67, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-05-06 */ // Sources flattened with hardhat v2.1.2 https://hardhat.org // File contracts/libraries/Ownable.sol pragma solidity ^0.7.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 public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @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 { _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/libraries/ReentrancyGuard.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/token/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/token/ERC20/IERC20.sol 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); } // File contracts/libraries/SafeMath.sol pragma solidity ^0.7.0; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @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 addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ 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 multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/token/ERC20/ERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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_) { _name = name_; _symbol = symbol_; _decimals = 18; _totalSupply = 1000000e18; } /** * @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 { } } // File contracts/token/ERC721/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.0 <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 contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File contracts/tier/RedKiteTiers.sol pragma solidity ^0.7.0; contract RedKiteTiers is IERC721Receiver, Ownable, ReentrancyGuard { using SafeMath for uint256; // Info of each user struct UserInfo { uint256 staked; // How many tokens the user has provided uint256 stakedTime; // Block timestamp when the user provided token } // RedKiteTiers allow to stake multi tokens to up your tier. Please // visit the website to get token list or use the token contract to // check it is supported or not. // Info of each Token // Currency Rate with PKF: amount * rate / 10 ** decimals // Default PKF: rate=1, decimals=0 struct ExternalToken { address contractAddress; uint256 decimals; uint256 rate; bool isERC721; bool canStake; } uint256 constant MAX_NUM_TIERS = 10; uint8 currentMaxTier = 4; // Address take user's withdraw fee address public penaltyWallet; // The POLKAFOUNDRY TOKEN! address public PKF; // Info of each user that stakes tokens mapping(address => mapping(address => UserInfo)) public userInfo; // Info of total Non-PKF token staked, converted with rate mapping(address => uint256) public userExternalStaked; // Minimum PKF need to stake each tier uint256[MAX_NUM_TIERS] tierPrice; // Percentage of penalties uint256[6] public withdrawFeePercent; // The maximum number of days of penalties uint256[5] public daysLockLevel; // Info of each token can stake mapping(address => ExternalToken) public externalToken; bool public canEmergencyWithdraw; event StakedERC20(address indexed user, address token, uint256 amount); event StakedSingleERC721( address indexed user, address token, uint128 tokenId ); event StakedBatchERC721( address indexed user, address token, uint128[] tokenIds ); event WithdrawnERC20( address indexed user, address token, uint256 indexed amount, uint256 fee, uint256 lastStakedTime ); event WithdrawnSingleERC721( address indexed user, address token, uint128 tokenId, uint256 lastStakedTime ); event WithdrawnBatchERC721( address indexed user, address token, uint128[] tokenIds, uint256 lastStakedTime ); event EmergencyWithdrawnERC20( address indexed user, address token, uint256 amount, uint256 lastStakedTime ); event EmergencyWithdrawnERC721( address indexed user, address token, uint128[] tokenIds, uint256 lastStakedTime ); event AddExternalToken( address indexed token, uint256 decimals, uint256 rate, bool isERC721, bool canStake ); event ExternalTokenStatsChange( address indexed token, uint256 decimals, uint256 rate, bool canStake ); event ChangePenaltyWallet(address indexed penaltyWallet); constructor(address _pkf, address _sPkf, address _uniLp, address _penaltyWallet) { owner = msg.sender; penaltyWallet = _penaltyWallet; PKF = _pkf; addExternalToken(_pkf, 0, 1 , false, true); addExternalToken(_sPkf, 0, 1, false, true); addExternalToken(_uniLp, 0, 150, false, true); tierPrice[1] = 500e18; tierPrice[2] = 5000e18; tierPrice[3] = 20000e18; tierPrice[4] = 60000e18; daysLockLevel[0] = 10 days; daysLockLevel[1] = 20 days; daysLockLevel[2] = 30 days; daysLockLevel[3] = 60 days; daysLockLevel[4] = 90 days; } function depositERC20(address _token, uint256 _amount) external nonReentrant() { if (_token == PKF) { IERC20(PKF).transferFrom(msg.sender, address(this), _amount); } else { require( externalToken[_token].canStake == true, "TIER::TOKEN_NOT_ACCEPTED" ); IERC20(_token).transferFrom(msg.sender, address(this), _amount); ExternalToken storage token = externalToken[_token]; userExternalStaked[msg.sender] = userExternalStaked[msg.sender].add( _amount.mul(token.rate).div(10**token.decimals) ); } userInfo[msg.sender][_token].staked = userInfo[msg.sender][_token] .staked .add(_amount); userInfo[msg.sender][_token].stakedTime = block.timestamp; emit StakedERC20(msg.sender, _token, _amount); } function depositSingleERC721(address _token, uint128 _tokenId) external nonReentrant() { require( externalToken[_token].canStake == true, "TIER::TOKEN_NOT_ACCEPTED" ); IERC721(_token).safeTransferFrom(msg.sender, address(this), _tokenId); ExternalToken storage token = externalToken[_token]; userExternalStaked[msg.sender] = userExternalStaked[msg.sender].add( token.rate ); userInfo[msg.sender][_token].staked = userInfo[msg.sender][_token] .staked .add(1); userInfo[msg.sender][_token].stakedTime = block.timestamp; emit StakedSingleERC721(msg.sender, _token, _tokenId); } function depositBatchERC721(address _token, uint128[] memory _tokenIds) external nonReentrant() { require( externalToken[_token].canStake == true, "TIER::TOKEN_NOT_ACCEPTED" ); _batchSafeTransferFrom(_token, msg.sender, address(this), _tokenIds); uint256 amount = _tokenIds.length; ExternalToken storage token = externalToken[_token]; userExternalStaked[msg.sender] = userExternalStaked[msg.sender].add( amount.mul(token.rate) ); userInfo[msg.sender][_token].staked = userInfo[msg.sender][_token] .staked .add(amount); userInfo[msg.sender][_token].stakedTime = block.timestamp; emit StakedBatchERC721(msg.sender, _token, _tokenIds); } function withdrawERC20(address _token, uint256 _amount) external nonReentrant() { UserInfo storage user = userInfo[msg.sender][_token]; require(user.staked >= _amount, "not enough amount to withdraw"); if (_token != PKF) { ExternalToken storage token = externalToken[_token]; userExternalStaked[msg.sender] = userExternalStaked[msg.sender].sub( _amount.mul(token.rate).div(10**token.decimals) ); } uint256 toPunish = calculateWithdrawFee(msg.sender, _token, _amount); if (toPunish > 0) { IERC20(_token).transfer(penaltyWallet, toPunish); } user.staked = user.staked.sub(_amount); IERC20(_token).transfer(msg.sender, _amount.sub(toPunish)); emit WithdrawnERC20( msg.sender, _token, _amount, toPunish, user.stakedTime ); } function withdrawSingleERC721(address _token, uint128 _tokenId) external nonReentrant() { UserInfo storage user = userInfo[msg.sender][_token]; require(user.staked >= 1, "not enough amount to withdraw"); user.staked = user.staked.sub(1); ExternalToken storage token = externalToken[_token]; userExternalStaked[msg.sender] = userExternalStaked[msg.sender].sub( token.rate ); IERC721(_token).safeTransferFrom(address(this), msg.sender, _tokenId); emit WithdrawnSingleERC721( msg.sender, _token, _tokenId, user.stakedTime ); } function withdrawBatchERC721(address _token, uint128[] memory _tokenIds) external nonReentrant() { UserInfo storage user = userInfo[msg.sender][_token]; uint256 amount = _tokenIds.length; require(user.staked >= amount, "not enough amount to withdraw"); user.staked = user.staked.sub(amount); ExternalToken storage token = externalToken[_token]; userExternalStaked[msg.sender] = userExternalStaked[msg.sender].sub( amount.mul(token.rate) ); _batchSafeTransferFrom(_token, address(this), msg.sender, _tokenIds); emit WithdrawnBatchERC721( msg.sender, _token, _tokenIds, user.stakedTime ); } function setPenaltyWallet(address _penaltyWallet) external onlyOwner { require( penaltyWallet != _penaltyWallet, "TIER::ALREADY_PENALTY_WALLET" ); penaltyWallet = _penaltyWallet; emit ChangePenaltyWallet(_penaltyWallet); } function updateEmergencyWithdrawStatus(bool _status) external onlyOwner { canEmergencyWithdraw = _status; } function emergencyWithdrawERC20(address _token) external { require(canEmergencyWithdraw, "function disabled"); UserInfo storage user = userInfo[msg.sender][_token]; require(user.staked > 0, "nothing to withdraw"); uint256 _amount = user.staked; user.staked = 0; if (_token != PKF) { ExternalToken storage token = externalToken[_token]; userExternalStaked[msg.sender] = userExternalStaked[msg.sender].sub( _amount.mul(token.rate).div(10**token.decimals) ); } IERC20(_token).transfer(msg.sender, _amount); emit EmergencyWithdrawnERC20( msg.sender, _token, _amount, user.stakedTime ); } function emergencyWithdrawERC721(address _token, uint128[] memory _tokenIds) external { require(canEmergencyWithdraw, "function disabled"); UserInfo storage user = userInfo[msg.sender][_token]; require(user.staked > 0, "nothing to withdraw"); uint256 _amount = user.staked; user.staked = 0; ExternalToken storage token = externalToken[_token]; userExternalStaked[msg.sender] = userExternalStaked[msg.sender].sub( _amount.mul(token.rate).div(10**token.decimals) ); if (_amount == 1) { IERC721(_token).safeTransferFrom( address(this), msg.sender, _tokenIds[0] ); } else { _batchSafeTransferFrom( _token, address(this), msg.sender, _tokenIds ); } emit EmergencyWithdrawnERC721( msg.sender, _token, _tokenIds, user.stakedTime ); } function addExternalToken( address _token, uint256 _decimals, uint256 _rate, bool _isERC721, bool _canStake ) public onlyOwner { ExternalToken storage token = externalToken[_token]; require(_rate > 0, "TIER::INVALID_TOKEN_RATE"); token.contractAddress = _token; token.decimals = _decimals; token.rate = _rate; token.isERC721 = _isERC721; token.canStake = _canStake; emit AddExternalToken(_token, _decimals, _rate, _isERC721, _canStake); } function setExternalToken( address _token, uint256 _decimals, uint256 _rate, bool _canStake ) external onlyOwner { ExternalToken storage token = externalToken[_token]; require(token.contractAddress == _token, "TIER::TOKEN_NOT_EXISTS"); require(_rate > 0, "TIER::INVALID_TOKEN_RATE"); token.decimals = _decimals; token.rate = _rate; token.canStake = _canStake; emit ExternalTokenStatsChange(_token, _decimals, _rate, _canStake); } function updateTier(uint8 _tierId, uint256 _amount) external onlyOwner { require(_tierId > 0 && _tierId <= MAX_NUM_TIERS, "invalid _tierId"); tierPrice[_tierId] = _amount; if (_tierId > currentMaxTier) { currentMaxTier = _tierId; } } function updateWithdrawFee(uint256 _key, uint256 _percent) external onlyOwner { require(_percent < 100, "too high percent"); withdrawFeePercent[_key] = _percent; } function updatePunishTime(uint256 _key, uint256 _days) external onlyOwner { require(_days >= 0, "too short time"); daysLockLevel[_key] = _days * 1 days; } function getUserTier(address _userAddress) external view returns (uint8 res) { uint256 totalStaked = userInfo[_userAddress][PKF].staked.add( userExternalStaked[_userAddress] ); for (uint8 i = 1; i <= MAX_NUM_TIERS; i++) { if (tierPrice[i] == 0 || totalStaked < tierPrice[i]) { return res; } res = i; } } function calculateWithdrawFee( address _userAddress, address _token, uint256 _amount ) public view returns (uint256) { UserInfo storage user = userInfo[_userAddress][_token]; require(user.staked >= _amount, "not enough amount to withdraw"); if (block.timestamp < user.stakedTime.add(daysLockLevel[0])) { return _amount.mul(withdrawFeePercent[0]).div(100); //30% } if (block.timestamp < user.stakedTime.add(daysLockLevel[1])) { return _amount.mul(withdrawFeePercent[1]).div(100); //25% } if (block.timestamp < user.stakedTime.add(daysLockLevel[2])) { return _amount.mul(withdrawFeePercent[2]).div(100); //20% } if (block.timestamp < user.stakedTime.add(daysLockLevel[3])) { return _amount.mul(withdrawFeePercent[3]).div(100); //10% } if (block.timestamp < user.stakedTime.add(daysLockLevel[4])) { return _amount.mul(withdrawFeePercent[4]).div(100); //5% } return _amount.mul(withdrawFeePercent[5]).div(100); } //frontend func function getTiers() external view returns (uint256[MAX_NUM_TIERS] memory buf) { for (uint8 i = 1; i < MAX_NUM_TIERS; i++) { if (tierPrice[i] == 0) { return buf; } buf[i - 1] = tierPrice[i]; } return buf; } function userTotalStaked(address _userAddress) external view returns (uint256) { return userInfo[_userAddress][PKF].staked.add( userExternalStaked[_userAddress] ); } function _batchSafeTransferFrom( address _token, address _from, address _recepient, uint128[] memory _tokenIds ) internal { for (uint256 i = 0; i != _tokenIds.length; i++) { IERC721(_token).safeTransferFrom(_from, _recepient, _tokenIds[i]); } } function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } }
Info of each Token Currency Rate with PKF: amount * rate / 10 ** decimals Default PKF: rate=1, decimals=0
struct ExternalToken { address contractAddress; uint256 decimals; uint256 rate; bool isERC721; bool canStake; } uint256 constant MAX_NUM_TIERS = 10; uint8 currentMaxTier = 4; bool public canEmergencyWithdraw; event StakedERC20(address indexed user, address token, uint256 amount); event StakedSingleERC721( address indexed user, address token, uint128 tokenId ); event StakedBatchERC721( address indexed user, address token, uint128[] tokenIds ); event WithdrawnERC20( address indexed user, address token, uint256 indexed amount, uint256 fee, uint256 lastStakedTime ); event WithdrawnSingleERC721( address indexed user, address token, uint128 tokenId, uint256 lastStakedTime ); event WithdrawnBatchERC721( address indexed user, address token, uint128[] tokenIds, uint256 lastStakedTime ); event EmergencyWithdrawnERC20( address indexed user, address token, uint256 amount, uint256 lastStakedTime ); event EmergencyWithdrawnERC721( address indexed user, address token, uint128[] tokenIds, uint256 lastStakedTime ); event AddExternalToken( address indexed token, uint256 decimals, uint256 rate, bool isERC721, bool canStake ); event ExternalTokenStatsChange( address indexed token, uint256 decimals, uint256 rate, bool canStake ); event ChangePenaltyWallet(address indexed penaltyWallet);
10,737,535
[ 1, 966, 434, 1517, 3155, 13078, 13025, 598, 11327, 42, 30, 3844, 225, 4993, 342, 1728, 225, 15105, 2989, 11327, 42, 30, 4993, 33, 21, 16, 15105, 33, 20, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 11352, 1345, 288, 203, 3639, 1758, 6835, 1887, 31, 203, 3639, 2254, 5034, 15105, 31, 203, 3639, 2254, 5034, 4993, 31, 203, 3639, 1426, 353, 654, 39, 27, 5340, 31, 203, 3639, 1426, 848, 510, 911, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 5381, 4552, 67, 6069, 67, 23240, 11367, 273, 1728, 31, 203, 565, 2254, 28, 783, 2747, 15671, 273, 1059, 31, 203, 203, 203, 203, 565, 1426, 1071, 848, 1514, 24530, 1190, 9446, 31, 203, 203, 565, 871, 934, 9477, 654, 39, 3462, 12, 2867, 8808, 729, 16, 1758, 1147, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 934, 9477, 5281, 654, 39, 27, 5340, 12, 203, 3639, 1758, 8808, 729, 16, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 10392, 1147, 548, 203, 565, 11272, 203, 565, 871, 934, 9477, 4497, 654, 39, 27, 5340, 12, 203, 3639, 1758, 8808, 729, 16, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 10392, 8526, 1147, 2673, 203, 565, 11272, 203, 565, 871, 3423, 9446, 82, 654, 39, 3462, 12, 203, 3639, 1758, 8808, 729, 16, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 8808, 3844, 16, 203, 3639, 2254, 5034, 14036, 16, 203, 3639, 2254, 5034, 1142, 510, 9477, 950, 203, 565, 11272, 203, 565, 871, 3423, 9446, 82, 5281, 654, 39, 27, 5340, 12, 203, 3639, 1758, 8808, 729, 16, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 10392, 1147, 548, 16, 203, 3639, 2254, 5034, 1142, 510, 9477, 950, 203, 565, 11272, 203, 565, 871, 3423, 2 ]
// SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.22 <0.9.0; // See https://github.com/luigidarco96/HealthcareEnabledBlockchain import "../common/Version.sol"; import "../common/Frozen.sol"; import "../libs/User.sol"; import "../libs/StringUtils.sol"; contract PersonalInfo is Version, Frozen { string public constant DEFAULT_ADMIN_ROLE = string("ADMIN_ROLE98765"); string public constant PATIENT_ROLE = string("PATIENT_ROLE98765"); // Record count uint public recordCount = 0; struct Record { uint id; uint SpO2; // blood oxygenation uint HR; // heart rate uint Systolic; // blood pressure - systolic uint Diastolic; // blood pressure = diastolic address owner; // owner's address, patient uint256 timestamp; } // List of records mapping(uint => Record) public records; constructor() { User.addUserByAddress(msg.sender); User.updateUserMeta("", "", "", "", "", DEFAULT_ADMIN_ROLE); User.updateUserMeta("", "", "", "", "", PATIENT_ROLE); } // Return `true` if the account belongs to the admin role. function isAdmin(address account) public virtual returns (bool) { return User.hasRole(DEFAULT_ADMIN_ROLE, account); } // Return `true` if the account belongs to the patient role. function isPatient(address account) public virtual returns (bool) { return User.hasRole(PATIENT_ROLE, account); } // Restricted to members of the admin role. modifier onlyAdmin() { require(isAdmin(msg.sender), "Restricted to admins."); _; } // Restricted to members of the patient role. modifier onlyPatient() { require(isPatient(msg.sender), "Restricted to patient."); _; } // Add an account to the user role. Restricted to admins. function addPatient(address account) public virtual onlyAdmin { User.grantRole(PATIENT_ROLE, account); } // Add an account to the admin role. Restricted to admins. function addAdmin(address account) public virtual onlyAdmin { User.grantRole(DEFAULT_ADMIN_ROLE, account); } // Remove an account from the patient role. Restricted to admins. function removePatient(address account) public virtual onlyAdmin { User.revokeRole(PATIENT_ROLE, account); } // Remove oneself from the admin role. function renounceAdmin() public virtual { User.renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } // Insert a record in the list function createRecord(uint256 _timestamp, uint _spO2, uint _hr, uint _systolic, uint _diastolic) public virtual onlyPatient { recordCount++; records[recordCount] = Record(recordCount, _spO2, _hr, _systolic, _diastolic, msg.sender, _timestamp); } // Read a record from the list function getRecord(uint _id) public view returns (uint, uint, uint, uint, uint, address, uint256) { Record memory currentRecord = records[_id]; return (currentRecord.id, currentRecord.SpO2, currentRecord.HR, currentRecord.Systolic, currentRecord.Diastolic, currentRecord.owner, currentRecord.timestamp); } }
Insert a record in the list
function createRecord(uint256 _timestamp, uint _spO2, uint _hr, uint _systolic, uint _diastolic) public virtual onlyPatient { recordCount++; records[recordCount] = Record(recordCount, _spO2, _hr, _systolic, _diastolic, msg.sender, _timestamp); }
12,760,280
[ 1, 4600, 279, 1409, 316, 326, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 2115, 12, 11890, 5034, 389, 5508, 16, 2254, 389, 1752, 51, 22, 16, 2254, 389, 7256, 16, 2254, 389, 87, 1094, 1415, 16, 2254, 389, 3211, 689, 1415, 13, 203, 3639, 1071, 203, 3639, 5024, 203, 3639, 1338, 22834, 1979, 203, 565, 288, 203, 3639, 1409, 1380, 9904, 31, 203, 3639, 3853, 63, 3366, 1380, 65, 273, 5059, 12, 3366, 1380, 16, 389, 1752, 51, 22, 16, 389, 7256, 16, 389, 87, 1094, 1415, 16, 389, 3211, 689, 1415, 16, 1234, 18, 15330, 16, 389, 5508, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.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/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; /** * @title MLXG Token Contract * * @dev MLXG Token Contract with custom Mint and redeem functions keepimg in view the bullion Standard it mints 400 tokens only per Certificate. * Also includes blocking of accounts, and multitransfers functionality. Blocked accounts cannot do transfers and Admin can destroy their funds multitransfer used to transfer to multiple addresses at once */ contract MLXG_token is Initializable, UUPSUpgradeable, ERC20Upgradeable, AccessControlUpgradeable, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { using Counters for Counters.Counter; event Mint(uint256 id); event NewPrivilegedContract(address indexed _contract); event RemovedPrivilegedContract(address indexed _contract); event Redeem(uint certificate_id); event DestroyedBlockedFunds(address indexed _blockedUser, uint _balance); event BlockPlaced(address indexed _user); event BlockReleased(address indexed _user); Counters.Counter public certificateCounter; uint256 constant weight_of_gold = 400; // 400 oz of London Good Delivery Gold bar bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); mapping (bytes32 => bool ) private certificate_hashes ; mapping (uint256 => certificate ) private certificate_record ; mapping (address => bool) public isTrusted; mapping (address => bool) public isBlocked; struct certificate { bool exists; uint256 certificate_id; uint256 weight_of_gold; bytes certificate_signature; bytes metadata; } // Reverts if called by a blocked account modifier onlyNotBlocked() { require(!isBlocked[_msgSender()], "Blocked: transfers are blocked for user"); _; } // MLXG Initializer function initialize() initializer public { __ERC20_init("Marvellex Gold", "MLXG"); __Ownable_init(); __AccessControl_init(); __Pausable_init(); __UUPSUpgradeable_init(); _setupRole(DEFAULT_ADMIN_ROLE, owner()); _setRoleAdmin(PAUSER_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(MINTER_ROLE, DEFAULT_ADMIN_ROLE); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(PAUSER_ROLE, msg.sender); _grantRole(MINTER_ROLE, msg.sender); } /** * @dev Used by new UUPS Proxy pattern to upgrade the contract. */ function _authorizeUpgrade(address newImplementation) internal onlyOwner override { } function pause() public onlyRole(PAUSER_ROLE) { _pause(); } function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } /** * @dev To read certificate Mapping. * @param _id, id of record to set * @return returns certificate_record stored in the contract against the _id */ function getCertificateRecord(uint256 _id) public view returns (certificate memory ){ return certificate_record[_id]; } /** * @dev MINTER can mint new tokens against a gold certificate. * * Requirements: - certificate_signature should be unique * @param to, address to which newly minted MLXG will be minted. * @param certificate_signature, signature of Certificate representing the bullion * @param metadata, metadata of certificate * @return id, returns the id of the certificate_record stored in the contract */ function mint(address to, bytes memory certificate_signature, bytes memory metadata ) public onlyRole(MINTER_ROLE) whenNotPaused() returns (uint256) { require( to != address(this), "ERC20: transfer to the contract address"); require(isUnique_by_Hash(certificate_signature) == true, "MLXG_token: Bullion id not Unique") ; certificate_hashes[keccak256(certificate_signature)] = true; certificateCounter.increment(); uint256 id = certificateCounter.current(); certificate_record [ id ] = certificate(true, id, weight_of_gold, certificate_signature, metadata); _mint(to, 400 ether); // 400 tokens will be minted; emit Mint(id); return id; } /** * @dev MINTER can refeem/burn tokens against the a gold certificate. * * Requirements: - certificate_id should exist and signature should be Unique * @param certificate_id, id the bullion * @param certificate_signature, signature of Certificate representing the bullion */ function burn(uint256 certificate_id, bytes memory certificate_signature ) public virtual onlyRole(MINTER_ROLE) whenNotPaused nonReentrant(){ require( certificate_record [ certificate_id ].exists == true, "Bullion with this ID does not exist" ); require( keccak256(certificate_record [ certificate_id ].certificate_signature) == keccak256(certificate_signature), "Signature Mismatch" ); _burn(msg.sender, 400 ether); certificate_record [ certificate_id ].exists = false; certificate_record [ certificate_id ].certificate_signature = bytes(""); emit Redeem(certificate_id); } function transfer(address _recipient, uint256 _amount) public virtual override onlyNotBlocked whenNotPaused nonReentrant() returns (bool) { require(_recipient != address(this), "ERC20: transfer to the contract address"); return super.transfer(_recipient, _amount); } /** * @dev Standard ERC20 function but it also returns if the address is trusted one or not. * * @param _sender, address sending the transfers. * @param _recipient, address to which transfers will be made. * @param _amount, _amount to transfer */ function transferFrom(address _sender, address _recipient, uint256 _amount) public virtual override whenNotPaused onlyNotBlocked nonReentrant() returns (bool) { require(_recipient != address(this), "ERC20: transfer to the contract address"); require(!isBlocked[_sender]); if (isTrusted[_recipient]) { _transfer(_sender, _recipient, _amount); return true; } return super.transferFrom(_sender, _recipient, _amount); } /** * @dev To make multiple transfers to multiple addresses. * * Requirements: - length of both arrays should be same * @param _recipients, address to which transfers will be made. * @param _values, corresponding values to transfer */ function multiTransfer(address[] memory _recipients, uint256[] memory _values) public whenNotPaused onlyNotBlocked { require(_recipients.length == _values.length , "ERC20: multiTransfer mismatch"); for (uint256 i = 0; i < _recipients.length; i++) { transfer(_recipients[i], _values[i]); } } /** * @dev Adds an address to blockList. * @param _user, address to block. */ function addToBlockedList (address _user) public onlyRole(DEFAULT_ADMIN_ROLE) { isBlocked[_user] = true; emit BlockPlaced(_user); } /** * @dev removes an address to blockList. * @param _user, address to remove. */ function removeFromBlockedList (address _user) public onlyRole(DEFAULT_ADMIN_ROLE) { isBlocked[_user] = false; emit BlockReleased(_user); } /** * @dev Adds an address to whitelist. * @param _trustedDeFiContract, address to whitelist. */ function addPrivilegedContract(address _trustedDeFiContract) public onlyRole(DEFAULT_ADMIN_ROLE) { isTrusted[_trustedDeFiContract] = true; emit NewPrivilegedContract(_trustedDeFiContract); } /** * @dev removes an address from whitelist. * @param _trustedDeFiContract, address to remove. */ function removePrivilegedContract(address _trustedDeFiContract) public onlyRole(DEFAULT_ADMIN_ROLE) { isTrusted[_trustedDeFiContract] = false; emit RemovedPrivilegedContract(_trustedDeFiContract); } /** * @dev To Destroy Funds of a blocked Account. * * Requirements: - Account must be blocked * @param _blockedUser, address to whose funds will be destroyed. */ function destroyBlockedFunds (address _blockedUser) public onlyRole(DEFAULT_ADMIN_ROLE) { require(isBlocked[_blockedUser]); uint blockedFunds = balanceOf(_blockedUser); _burn(_blockedUser, blockedFunds); emit DestroyedBlockedFunds(_blockedUser, blockedFunds); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused override { super._beforeTokenTransfer(from, to, amount); } /** * @dev Used to check uniqueness of certificate_Signaturess. * @param _tokenURI, bytes data to check for uniqueness. */ function isUnique_by_Hash(bytes memory _tokenURI ) private view returns (bool) { if (certificate_hashes[keccak256(_tokenURI)] == true){ return false; }else{ return true; } } }
@param certificate_id, id the bullion @param certificate_signature, signature of Certificate representing the bullion/
function burn(uint256 certificate_id, bytes memory certificate_signature ) public virtual onlyRole(MINTER_ROLE) whenNotPaused nonReentrant(){ require( certificate_record [ certificate_id ].exists == true, "Bullion with this ID does not exist" ); require( keccak256(certificate_record [ certificate_id ].certificate_signature) == keccak256(certificate_signature), "Signature Mismatch" ); _burn(msg.sender, 400 ether); certificate_record [ certificate_id ].exists = false; certificate_record [ certificate_id ].certificate_signature = bytes(""); emit Redeem(certificate_id); }
15,833,457
[ 1, 14108, 67, 350, 16, 612, 326, 324, 420, 285, 225, 4944, 67, 8195, 16, 3372, 434, 6660, 5123, 326, 324, 420, 285, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 12, 11890, 5034, 4944, 67, 350, 16, 1731, 3778, 4944, 67, 8195, 225, 262, 1071, 5024, 1338, 2996, 12, 6236, 2560, 67, 16256, 13, 1347, 1248, 28590, 1661, 426, 8230, 970, 1435, 95, 203, 3639, 2583, 12, 4944, 67, 3366, 306, 4944, 67, 350, 308, 18, 1808, 422, 638, 16, 315, 38, 420, 285, 598, 333, 1599, 1552, 486, 1005, 6, 11272, 7010, 3639, 2583, 12, 417, 24410, 581, 5034, 12, 14108, 67, 3366, 306, 4944, 67, 350, 308, 18, 14108, 67, 8195, 13, 422, 417, 24410, 581, 5034, 12, 14108, 67, 8195, 3631, 315, 5374, 16584, 1916, 6, 11272, 7010, 3639, 389, 70, 321, 12, 3576, 18, 15330, 16, 7409, 225, 2437, 1769, 203, 3639, 4944, 67, 3366, 306, 4944, 67, 350, 308, 18, 1808, 273, 629, 31, 203, 3639, 4944, 67, 3366, 306, 4944, 67, 350, 308, 18, 14108, 67, 8195, 273, 1731, 2932, 8863, 203, 3639, 3626, 868, 24903, 12, 14108, 67, 350, 1769, 203, 225, 289, 203, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x98061d960c2EaA127cB1921a6f912A2Ebb981Db4/sources/src/DonationHandlerRoles.sol
@notice Wrapper function to check if an address is admin. @param _account The address to check. @return bool True if address is admin, false otherwise.
function isAdmin(address _account) external view returns (bool) { return hasRole(ADMIN, _account); }
11,624,827
[ 1, 3611, 445, 358, 866, 309, 392, 1758, 353, 3981, 18, 225, 389, 4631, 1021, 1758, 358, 866, 18, 327, 1426, 1053, 309, 1758, 353, 3981, 16, 629, 3541, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23467, 12, 2867, 389, 4631, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 28335, 12, 15468, 16, 389, 4631, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol"; import {TBTCDepositToken} from "../system/TBTCDepositToken.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; import {VendingMachine} from "../system/VendingMachine.sol"; /// @notice A one-click script for minting TBTC from an unqualified TDT. /// @dev Wrapper script for VendingMachine.unqualifiedDepositToTbtc /// This contract implements receiveApproval() and can therefore use /// approveAndCall(). This pattern combines TBTC Token approval and /// vendingMachine.unqualifiedDepositToTbtc() in a single transaction. contract FundingScript is ITokenRecipient { TBTCToken tbtcToken; VendingMachine vendingMachine; TBTCDepositToken tbtcDepositToken; FeeRebateToken feeRebateToken; constructor( address _VendingMachine, address _TBTCToken, address _TBTCDepositToken, address _FeeRebateToken ) public { vendingMachine = VendingMachine(_VendingMachine); tbtcToken = TBTCToken(_TBTCToken); tbtcDepositToken = TBTCDepositToken(_TBTCDepositToken); feeRebateToken = FeeRebateToken(_FeeRebateToken); } /// @notice Receives approval for a TDT transfer, and calls `VendingMachine.unqualifiedDepositToTbtc` for a user. /// @dev Implements the approveAndCall receiver interface. /// @param _from The owner of the token who approved them for transfer. /// @param _tokenId Approved TDT for the transfer. /// @param _extraData Encoded function call to `VendingMachine.unqualifiedDepositToTbtc`. function receiveApproval( address _from, uint256 _tokenId, address, bytes memory _extraData ) public { // not external to allow bytes memory parameters require(msg.sender == address(tbtcDepositToken), "Only token contract can call receiveApproval"); tbtcDepositToken.transferFrom(_from, address(this), _tokenId); tbtcDepositToken.approve(address(vendingMachine), _tokenId); // Verify _extraData is a call to unqualifiedDepositToTbtc. bytes4 functionSignature; assembly { functionSignature := and(mload(add(_extraData, 0x20)), not(0xff)) } require( functionSignature == vendingMachine.unqualifiedDepositToTbtc.selector, "Bad _extraData signature. Call must be to unqualifiedDepositToTbtc." ); // Call the VendingMachine. // We could explictly encode the call to vending machine, but this would // involve manually parsing _extraData and allocating variables. // We capture the `returnData` in order to forward any nested revert message // from the contract call. /* solium-disable-next-line security/no-low-level-calls */ (bool success, bytes memory returnData) = address(vendingMachine).call(_extraData); string memory revertMessage; assembly { // A revert message is ABI-encoded as a call to Error(string). // Slicing the Error() signature (4 bytes) and Data offset (4 bytes) // leaves us with a pre-encoded string. // We also slice off the ABI-coded length of returnData (32). revertMessage := add(returnData, 0x44) } require(success, revertMessage); // Transfer the TBTC and feeRebateToken to the user. tbtcToken.transfer(_from, tbtcToken.balanceOf(address(this))); feeRebateToken.transferFrom(address(this), _from, uint256(_tokenId)); } }
@notice A one-click script for minting TBTC from an unqualified TDT. @dev Wrapper script for VendingMachine.unqualifiedDepositToTbtc This contract implements receiveApproval() and can therefore use approveAndCall(). This pattern combines TBTC Token approval and vendingMachine.unqualifiedDepositToTbtc() in a single transaction.
contract FundingScript is ITokenRecipient { TBTCToken tbtcToken; VendingMachine vendingMachine; TBTCDepositToken tbtcDepositToken; FeeRebateToken feeRebateToken; constructor( address _VendingMachine, address _TBTCToken, address _TBTCDepositToken, address _FeeRebateToken import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol"; import {TBTCDepositToken} from "../system/TBTCDepositToken.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; import {VendingMachine} from "../system/VendingMachine.sol"; ) public { vendingMachine = VendingMachine(_VendingMachine); tbtcToken = TBTCToken(_TBTCToken); tbtcDepositToken = TBTCDepositToken(_TBTCDepositToken); feeRebateToken = FeeRebateToken(_FeeRebateToken); } function receiveApproval( address _from, uint256 _tokenId, address, bytes memory _extraData require(msg.sender == address(tbtcDepositToken), "Only token contract can call receiveApproval"); tbtcDepositToken.transferFrom(_from, address(this), _tokenId); tbtcDepositToken.approve(address(vendingMachine), _tokenId); bytes4 functionSignature; assembly { functionSignature := and(mload(add(_extraData, 0x20)), not(0xff)) } require( functionSignature == vendingMachine.unqualifiedDepositToTbtc.selector, "Bad _extraData signature. Call must be to unqualifiedDepositToTbtc." ); (bool success, bytes memory returnData) = address(vendingMachine).call(_extraData); string memory revertMessage; assembly { revertMessage := add(returnData, 0x44) } require(success, revertMessage); feeRebateToken.transferFrom(address(this), _from, uint256(_tokenId)); tbtcToken.transfer(_from, tbtcToken.balanceOf(address(this))); }
885,046
[ 1, 37, 1245, 17, 7475, 2728, 364, 312, 474, 310, 399, 38, 15988, 628, 392, 640, 19724, 399, 9081, 18, 225, 18735, 2728, 364, 776, 2846, 6981, 18, 318, 19724, 758, 1724, 774, 56, 70, 5111, 1220, 6835, 4792, 6798, 23461, 1435, 471, 848, 13526, 999, 6617, 537, 1876, 1477, 7675, 1220, 1936, 30933, 399, 38, 15988, 3155, 23556, 471, 331, 2846, 6981, 18, 318, 19724, 758, 1724, 774, 56, 70, 5111, 1435, 316, 279, 2202, 2492, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 478, 14351, 3651, 353, 467, 1345, 18241, 288, 203, 565, 399, 38, 56, 1268, 969, 8739, 5111, 1345, 31, 203, 565, 776, 2846, 6981, 331, 2846, 6981, 31, 203, 565, 399, 38, 15988, 758, 1724, 1345, 8739, 5111, 758, 1724, 1345, 31, 203, 565, 30174, 426, 70, 340, 1345, 14036, 426, 70, 340, 1345, 31, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 58, 2846, 6981, 16, 203, 3639, 1758, 389, 25730, 56, 1268, 969, 16, 203, 3639, 1758, 389, 25730, 15988, 758, 1724, 1345, 16, 203, 3639, 1758, 389, 14667, 426, 70, 340, 1345, 203, 5666, 288, 1285, 969, 18241, 97, 628, 315, 6216, 15898, 19, 1285, 969, 18241, 18, 18281, 14432, 203, 5666, 288, 25730, 15988, 758, 1724, 1345, 97, 628, 315, 6216, 4299, 19, 25730, 15988, 758, 1724, 1345, 18, 18281, 14432, 203, 5666, 288, 25730, 56, 1268, 969, 97, 628, 315, 6216, 4299, 19, 25730, 56, 1268, 969, 18, 18281, 14432, 203, 5666, 288, 14667, 426, 70, 340, 1345, 97, 628, 315, 6216, 4299, 19, 14667, 426, 70, 340, 1345, 18, 18281, 14432, 203, 5666, 288, 58, 2846, 6981, 97, 628, 315, 6216, 4299, 19, 58, 2846, 6981, 18, 18281, 14432, 203, 565, 262, 1071, 288, 203, 3639, 331, 2846, 6981, 273, 776, 2846, 6981, 24899, 58, 2846, 6981, 1769, 203, 3639, 8739, 5111, 1345, 273, 399, 38, 56, 1268, 969, 24899, 25730, 56, 1268, 969, 1769, 203, 3639, 8739, 5111, 758, 1724, 1345, 273, 399, 38, 15988, 758, 1724, 1345, 24899, 25730, 15988, 758, 1724, 1345, 1769, 2 ]
./partial_match/137/0x48304908669633459c9381CB538Ff7bffF3a8e43/sources/darkUSD.sol
Used by pools when user redeems
function pool_burn_from(address b_address, uint256 b_amount) public onlyPools { super._burnFrom(b_address, b_amount); emit dUSDBurned(b_address, msg.sender, b_amount); }
3,525,555
[ 1, 6668, 635, 16000, 1347, 729, 283, 323, 7424, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2845, 67, 70, 321, 67, 2080, 12, 2867, 324, 67, 2867, 16, 2254, 5034, 324, 67, 8949, 13, 1071, 1338, 16639, 288, 203, 3639, 2240, 6315, 70, 321, 1265, 12, 70, 67, 2867, 16, 324, 67, 8949, 1769, 203, 3639, 3626, 302, 3378, 2290, 321, 329, 12, 70, 67, 2867, 16, 1234, 18, 15330, 16, 324, 67, 8949, 1769, 203, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../ExodiaAccessControlInitializable.sol"; import "../IPriceOracle.sol"; import "../../IPriceProvider.sol"; import "../../interfaces/IBalV2PriceOracle.sol"; import "../../../interfaces/IBPoolV2.sol"; import "../../../interfaces/IBVaultV2.sol"; contract BalancerV2WeightedPoolPriceOracle is IPriceOracle, ExodiaAccessControlInitializable { uint256 public constant VERSION = 2022040401; address public constant FTM = address(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83); IBVaultV2 public vault; IPriceProvider public priceProvider; uint256 public ratioDiffLimitNumerator; uint256 public ratioDiffLimitDenominator; event SetRatioDiffLimit( uint256 ratioDiffLimitNumerator, uint256 ratioDiffLimitDenominator ); /** * @dev sets up the Price Oracle * @param _roles exodia roles address * @param _vault balancer vault address */ function initialize( address _roles, address _vault, address _priceProvider ) public initializer { require(_vault != address(0), "vault cannot be null address"); require(_priceProvider != address(0), "price provider cannot be null address"); ExodiaAccessControlInitializable.initializeAccessControl(_roles); vault = IBVaultV2(_vault); priceProvider = IPriceProvider(_priceProvider); } /** * @dev set ratio difference limit */ function setRatioDiffLimit( uint256 _ratioDiffLimitNumerator, uint256 _ratioDiffLimitDenominator ) external onlyArchitect { require( _ratioDiffLimitNumerator <= _ratioDiffLimitDenominator, "INVALID RATIO DIFF LIMIT" ); ratioDiffLimitNumerator = _ratioDiffLimitNumerator; ratioDiffLimitDenominator = _ratioDiffLimitDenominator; emit SetRatioDiffLimit(_ratioDiffLimitNumerator, _ratioDiffLimitDenominator); } /****** OPERATIONAL METHODS ******/ /** * @dev returns the TWAP for the provided pair as of the last update */ function getSafePrice(address _bpt) public view returns (uint256) { return _getLPPrice(_bpt, true); } /** * @dev returns the current "unsafe" price that can be easily manipulated */ function getCurrentPrice(address _bpt) external view returns (uint256) { return _getLPPrice(_bpt, false); } /** * @dev updates the TWAP (if enough time has lapsed) and returns the current safe price */ function updateSafePrice(address _bpt) external returns (uint256) { return getSafePrice(_bpt); } // internal functions function _getTokenSafePrice(address token) internal view returns (uint256 price) { price = 10**18; if (FTM != token) { price = priceProvider.getSafePrice(token); } } function _getTokenCurrentPrice(address token) internal view returns (uint256 price) { price = 10**18; if (FTM != token) { price = priceProvider.getCurrentPrice(token); } } function _getLPPrice(address _bpt, bool isSafePrice) internal view returns (uint256 price) { bytes32 poolId = IBPoolV2(_bpt).getPoolId(); uint256[] memory weights = IBPoolV2(_bpt).getNormalizedWeights(); uint256 totalSupply = IBPoolV2(_bpt).totalSupply(); (IERC20[] memory tokens, uint256[] memory balances, ) = vault.getPoolTokens( poolId ); uint256 totalFTM; uint256[] memory prices = new uint256[](tokens.length); // update balances in 18 decimals for (uint256 i = 0; i < tokens.length; i++) { balances[i] = (balances[i] * (10**18)) / (10**ERC20(address(tokens[i])).decimals()); prices[i] = isSafePrice ? _getTokenSafePrice(address(tokens[i])) : _getTokenCurrentPrice(address(tokens[i])); if (i >= 1) { _checkRatio( (balances[i - 1] * 10**18) / weights[i - 1], (balances[i] * 10**18) / weights[i], prices[i - 1], prices[i] ); } totalFTM += balances[i] * prices[i]; } price = totalFTM / totalSupply; } function _checkRatio( uint256 reserve0, uint256 reserve1, uint256 price0, uint256 price1 ) internal view { uint256 value0 = reserve0 * price0; uint256 value1 = reserve1 * price1; uint256 diffLimit = (value0 * ratioDiffLimitNumerator) / ratioDiffLimitDenominator; require( value1 < value0 + diffLimit && value0 < value1 + diffLimit, "INVALID RATIO" ); } }
* @dev updates the TWAP (if enough time has lapsed) and returns the current safe price/
function updateSafePrice(address _bpt) external returns (uint256) { return getSafePrice(_bpt); }
6,361,996
[ 1, 14703, 326, 24722, 2203, 261, 430, 7304, 813, 711, 328, 8676, 13, 471, 1135, 326, 783, 4183, 6205, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 9890, 5147, 12, 2867, 389, 70, 337, 13, 3903, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1322, 2513, 5147, 24899, 70, 337, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x4a41711E525027daF866D3Dc1ca99ac8e7e506Ec/sources/MemeTools.sol
block number of opened trading exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract MemeTools is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address private marketingWallet; address private devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = true; bool public swapEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; uint256 launchedAt; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public partners; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event Setpartner(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("MemeTools","$Tools") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setpartner(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1 * 1e9 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable { } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; launchedAt = block.number; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateBuyFees( uint256 _devFee, uint256 _liquidityFee, uint256 _marketingFee ) external onlyOwner { buyDevFee = _devFee; buyLiquidityFee = _liquidityFee; buyMarketingFee = _marketingFee; buyTotalFees = buyDevFee + buyLiquidityFee + buyMarketingFee; require(buyTotalFees <= 10, "Must keep fees at 10% or less"); } function updateSellFees( uint256 _devFee, uint256 _liquidityFee, uint256 _marketingFee ) external onlyOwner { sellDevFee = _devFee; sellLiquidityFee = _liquidityFee; sellMarketingFee = _marketingFee; sellTotalFees = sellDevFee + sellLiquidityFee + sellMarketingFee; require(sellTotalFees <= 90, "Must keep fees at 90% or less"); } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setpartner(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from partners"); _setpartner(pair, value); } function _setpartner(address pair, bool value) private { partners[pair] = value; emit Setpartner(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (partners[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (partners[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !partners[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (partners[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(partners[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(this), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; (success,) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingWallet).call{value: address(this).balance}(""); }
9,241,419
[ 1, 2629, 1300, 434, 10191, 1284, 7459, 4433, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 490, 4698, 10348, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 7010, 565, 1426, 3238, 7720, 1382, 31, 203, 7010, 565, 1758, 3238, 13667, 310, 16936, 31, 203, 565, 1758, 3238, 4461, 16936, 31, 203, 7010, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 7010, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 638, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 638, 31, 203, 7010, 377, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 8870, 14667, 31, 203, 7010, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 357, 80, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 8870, 14667, 31, 203, 7010, 565, 2254, 5034, 1071, 2430, 1290, 3882, 21747, 31, 203, 565, 2254, 5034, 1071, 2430, 1290, 48, 18988, 24237, 31, 203, 565, 2254, 5034, 1071, 2430, 2 ]
./full_match/1/0x19682A5e90Be8221C1AFa75Fd326A691c6e16d0a/sources/contracts/TestEditionV1.sol
* @notice Distribute funds between the derivative fee recipient and proceeds recipient @dev This function should be called as part of any purchase function, with all funds in msg.value distributed here @param totalFunds Amount of funds to be distributed @param quantity Quantity of tokens purchased/
function _distributeFunds(uint256 totalFunds, uint256 quantity) internal { uint256 totalDerivativeFee = DERIVATIVE_FEE * quantity; require(feeSuccess, "Failed to send derivative fee"); emit DerivativeFeePayout({ value: totalDerivativeFee, recipient: derivativeFeeRecipient }); uint256 proceeds = totalFunds - totalDerivativeFee; if (proceeds > 0) { require(proceedsSuccess, "Failed to send purchase proceeds"); emit ProceedsPayout({ value: proceeds, recipient: creatorProceedRecipient }); } }
9,804,418
[ 1, 1669, 887, 284, 19156, 3086, 326, 16417, 14036, 8027, 471, 11247, 87, 8027, 225, 1220, 445, 1410, 506, 2566, 487, 1087, 434, 1281, 23701, 445, 16, 598, 777, 284, 19156, 316, 1234, 18, 1132, 16859, 2674, 225, 2078, 42, 19156, 16811, 434, 284, 19156, 358, 506, 16859, 225, 10457, 18189, 434, 2430, 5405, 343, 8905, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2251, 887, 42, 19156, 12, 11890, 5034, 2078, 42, 19156, 16, 2254, 5034, 10457, 13, 2713, 288, 203, 3639, 2254, 5034, 2078, 26239, 1535, 14667, 273, 21801, 8188, 12992, 67, 8090, 41, 380, 10457, 31, 203, 3639, 2583, 12, 21386, 4510, 16, 315, 2925, 358, 1366, 16417, 14036, 8863, 203, 203, 3639, 3626, 14969, 427, 1535, 14667, 52, 2012, 12590, 203, 5411, 460, 30, 2078, 26239, 1535, 14667, 16, 203, 5411, 8027, 30, 16417, 14667, 18241, 203, 3639, 15549, 203, 203, 3639, 2254, 5034, 11247, 87, 273, 2078, 42, 19156, 300, 2078, 26239, 1535, 14667, 31, 203, 3639, 309, 261, 685, 5288, 87, 405, 374, 13, 288, 203, 5411, 2583, 12, 685, 5288, 87, 4510, 16, 315, 2925, 358, 1366, 23701, 11247, 87, 8863, 203, 203, 5411, 3626, 1186, 5288, 87, 52, 2012, 12590, 203, 7734, 460, 30, 11247, 87, 16, 203, 7734, 8027, 30, 11784, 626, 5288, 18241, 203, 5411, 15549, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.21 <0.7.0; /** * @notice Key sets with enumeration and delete. Uses mappings for random * and existence checks and dynamic arrays for enumeration. Key uniqueness is enforced. * @dev Sets are unordered. Delete operations reorder keys. All operations have a * fixed gas cost at any scale, O(1). */ library StringSet { struct Set { mapping(bytes32 => uint) keyPointers; mapping(bytes32 => string) strings; string[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, string memory key) internal { require(!exists(self, key), "StringSet: key already exists in the set."); self.keyList.push(key); self.keyPointers[toBytes32(key)] = self.keyList.length-1; } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, string memory key) internal { require(exists(self, key), "StringSet: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[toBytes32(key)]; if(rowToReplace != last) { string memory keyToMove = self.keyList[last]; self.keyPointers[toBytes32(keyToMove)] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[toBytes32(key)]; self.keyList.pop(); } function count(Set storage self) internal view returns(uint) { return(self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, string memory key) internal view returns (bool) { if(self.keyList.length == 0) return false; return toBytes32(self.keyList[self.keyPointers[toBytes32(key)]]) == toBytes32(key); } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint index) internal view returns (string memory) { return self.keyList[index]; } function toBytes32(string memory s) private pure returns (bytes32) { return(keccak256(bytes(s))); } }
* @notice remove a key. @dev key to remove must exist. @param self storage pointer to a Set. @param key value to remove./
function remove(Set storage self, string memory key) internal { require(exists(self, key), "StringSet: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[toBytes32(key)]; if(rowToReplace != last) { string memory keyToMove = self.keyList[last]; self.keyPointers[toBytes32(keyToMove)] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[toBytes32(key)]; self.keyList.pop(); }
12,995,123
[ 1, 4479, 279, 498, 18, 225, 498, 358, 1206, 1297, 1005, 18, 225, 365, 2502, 4407, 358, 279, 1000, 18, 225, 498, 460, 358, 1206, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 12, 694, 2502, 365, 16, 533, 3778, 498, 13, 2713, 288, 203, 3639, 2583, 12, 1808, 12, 2890, 16, 498, 3631, 315, 780, 694, 30, 498, 1552, 486, 1005, 316, 326, 444, 1199, 1769, 203, 3639, 2254, 1142, 273, 1056, 12, 2890, 13, 300, 404, 31, 203, 3639, 2254, 1027, 774, 5729, 273, 365, 18, 856, 27452, 63, 869, 2160, 1578, 12, 856, 13, 15533, 203, 3639, 309, 12, 492, 774, 5729, 480, 1142, 13, 288, 203, 5411, 533, 3778, 498, 774, 7607, 273, 365, 18, 856, 682, 63, 2722, 15533, 203, 5411, 365, 18, 856, 27452, 63, 869, 2160, 1578, 12, 856, 774, 7607, 25887, 273, 1027, 774, 5729, 31, 203, 5411, 365, 18, 856, 682, 63, 492, 774, 5729, 65, 273, 498, 774, 7607, 31, 203, 3639, 289, 203, 3639, 1430, 365, 18, 856, 27452, 63, 869, 2160, 1578, 12, 856, 13, 15533, 203, 3639, 365, 18, 856, 682, 18, 5120, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract FixedStaking is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // user deposits are recorded in StakeInfo[] stakes struct struct StakeInfo { // staked is true if deposit is staked and hasn't been unstaked. // After user claims his stake back, `staked` becomes false bool staked; // stakedAmount get recorded at the stake time and doesn't change. uint256 stakedAmount; uint256 startTime; // endTime and totalYield get calculated in advance at the moment of staking // endTime is the date when unstaking becomes possible (without penalties) uint256 endTime; // totalYield is a total value of rewards for the given stake. // Gets calculated on the stake start and doesnt' change // but the amount that user is able to withdraw gets gradually unlocked over time. uint256 totalYield; // The amount of yield user already harvested and the time of last harvest call. uint256 harvestedYield; uint256 lastHarvestTime; } // If stakesOpen == true, the contract is operational and accepts new stakes. // Otherwise it allows just harvesting and unstaking. bool public stakesOpen; // The token accepted for staking and used for rewards (The same token for both). IERC20 public token; // struccture that stores the records of users' stakes mapping(address => StakeInfo[]) public stakes; // the total number of staked tokens. Accounted separately to avoid mixing stake and reward balances uint256 public stakedTokens; // The staking interval in days. // Early unstaking is possible but a fine is withheld. uint256 public stakeDurationDays; // Fee for early unstake in basis points (1/10000) // If the user withdraws before stake expiration, he pays `earlyUnstakeFee` uint256 public earlyUnstakeFee; // Reward that staker will receive for his stake // nominated in basis points (1/10000) of staked amount uint256 public yieldRate; // Yield tokens reserved for existing stakes to pay on harvest. // The reward tokens get allocated at the moment of stake. uint256 public allocatedTokens; // unallocated (excess) tokens can be withdrawn by the contract owner not earlier than 18 months uint256 public constant WITHDRAWAL_LOCKUP_DURATION = 30 days * 18; uint256 public withdrawalUnlockTime; event Stake(address indexed user, uint256 indexed stakeId, uint256 amount, uint256 startTime, uint256 endTime); event Unstake(address indexed user, uint256 indexed stakeId, uint256 amount, uint256 startTime, uint256 endTime, bool early); event Harvest(address indexed user, uint256 indexed stakeId, uint256 amount, uint256 harvestTime); /** * @dev the constructor arguments: * @param _token address of token - the same accepted for staking and used to pay rewards * @param _stakeDurationDays the stake duration in days * @param _yieldRate reward rate in basis points (1/10000) * @param _earlyUnstakeFee fee for unstaking before stake expiration */ constructor( address _token, uint256 _stakeDurationDays, uint256 _yieldRate, uint256 _earlyUnstakeFee ) { require(_token != address(0), "Empty token address"); require(_yieldRate > 0, "Zero yield rate"); require(_earlyUnstakeFee > 0, "Zero early Unstake Fee"); token = IERC20(_token); stakeDurationDays = _stakeDurationDays; yieldRate = _yieldRate; earlyUnstakeFee = _earlyUnstakeFee; withdrawalUnlockTime = _now().add(WITHDRAWAL_LOCKUP_DURATION); } /** * @dev the owner is able to withdraw excess tokens to collect early unstake fees or to reuse unused funds * suitable for assets rebalancing between staking contracts. * @param _to address who will receive the funds * @param _amount amount of tokens in atto (1e-18) units */ function withdrawUnallocatedTokens(address _to, uint256 _amount) public onlyOwner { require(_to != address(0), "Empty receiver address"); require(_amount > 0, "Zero amount"); require(unallocatedTokens() >= _amount, "Not enough unallocatedTokens"); require(_now() >= withdrawalUnlockTime, "Can't withdraw until withdrawalUnlockTime"); token.safeTransfer(_to, _amount); } /** * @dev start accepting new stakes. Called only by the owner */ function start() public onlyOwner { require(!stakesOpen, "Stakes are open already"); stakesOpen = true; } /** * @dev stop accepting new stakes. Called only by the owner */ function stop() public onlyOwner { require(stakesOpen, "Stakes are stopped already"); stakesOpen = false; } /** * @dev submit the stake * @param _amount amount of tokens to be transferred from user's account */ function stake(uint256 _amount) external { require(stakesOpen, "stake: not open"); require(_amount > 0, "stake: zero amount"); // entire reward allocated for the user for this stake uint256 totalYield = _amount.mul(yieldRate).div(10000); require(unallocatedTokens() >= totalYield, "stake: not enough allotted tokens to pay yield"); uint256 startTime = _now(); uint256 endTime = _now().add(stakeDurationDays.mul(1 days)); stakes[msg.sender].push( StakeInfo({ staked: true, stakedAmount: _amount, startTime: startTime, endTime: endTime, totalYield: totalYield, harvestedYield: 0, lastHarvestTime: startTime }) ); allocatedTokens = allocatedTokens.add(totalYield); stakedTokens = stakedTokens.add(_amount); uint256 stakeId = getStakesLength(msg.sender).sub(1); emit Stake(msg.sender, stakeId, _amount, startTime, endTime); token.safeTransferFrom(msg.sender, address(this), _amount); } /** * @dev withdraw the `body` of user's stake. Can be called only once * @param _stakeId Id of the stake */ function unstake(uint256 _stakeId) external { ( bool staked, uint256 stakedAmount, uint256 startTime, uint256 endTime, uint256 totalYield, uint256 harvestedYield, , uint256 harvestableYield ) = getStake(msg.sender, _stakeId); bool early; require(staked, "Unstaked already"); if (_now() > endTime) { stakes[msg.sender][_stakeId].staked = false; stakedTokens = stakedTokens.sub(stakedAmount); early = false; token.safeTransfer(msg.sender, stakedAmount); } else { uint256 newTotalYield = harvestedYield.add(harvestableYield); allocatedTokens = allocatedTokens.sub(totalYield.sub(newTotalYield)); stakes[msg.sender][_stakeId].staked = false; stakes[msg.sender][_stakeId].endTime = _now(); stakes[msg.sender][_stakeId].totalYield = newTotalYield; stakedTokens = stakedTokens.sub(stakedAmount); early = true; uint256 fee = stakedAmount.mul(earlyUnstakeFee).div(10000); uint256 amountToTransfer = stakedAmount.sub(fee); token.safeTransfer(msg.sender, amountToTransfer); } emit Unstake(msg.sender, _stakeId, stakedAmount, startTime, endTime, early); } /** * @dev harvest accumulated rewards. Can be called many times. * @param _stakeId Id of the stake */ function harvest(uint256 _stakeId) external { (, , , , , uint256 harvestedYield, , uint256 harvestableYield) = getStake(msg.sender, _stakeId); require(harvestableYield != 0, "harvestableYield is zero"); allocatedTokens = allocatedTokens.sub(harvestableYield); stakes[msg.sender][_stakeId].harvestedYield = harvestedYield.add(harvestableYield); stakes[msg.sender][_stakeId].lastHarvestTime = _now(); emit Harvest(msg.sender, _stakeId, harvestableYield, _now()); token.safeTransfer(msg.sender, harvestableYield); } /** * @dev get the amount of available tokens neither staked nor allocated for rewards * @return amount of unallocated tokens */ function unallocatedTokens() public view returns (uint256) { return token.balanceOf(address(this)).sub(stakedTokens).sub(allocatedTokens); } /** * @dev get the count of user's stakes. Used on frontend to iterate and display individual stakes * @param _userAddress account of staker * @return stakes */ function getStakesLength(address _userAddress) public view returns (uint256) { return stakes[_userAddress].length; } /** * @dev get the individual stake parameters of the user * @param _userAddress account of staker * @param _stakeId stake index * @return staked the status of stake * @return stakedAmount the number of deposited tokens * @return startTime the moment of stake start * @return endTime the time when unstaking (w.o. penalties) becomes possible * @return totalYield entire yield for the stake (totally released on endTime) * @return harvestedYield The part of yield user harvested already * @return lastHarvestTime The time of last harvest event * @return harvestableYield The unlocked part of yield available for harvesting */ function getStake(address _userAddress, uint256 _stakeId) public view returns ( bool staked, uint256 stakedAmount, uint256 startTime, uint256 endTime, uint256 totalYield, // Entire yield for the stake (totally released on endTime) uint256 harvestedYield, // The part of yield user harvested already uint256 lastHarvestTime, // The time of last harvest event uint256 harvestableYield // The unlocked part of yield available for harvesting ) { StakeInfo memory _stake = stakes[_userAddress][_stakeId]; staked = _stake.staked; stakedAmount = _stake.stakedAmount; startTime = _stake.startTime; endTime = _stake.endTime; totalYield = _stake.totalYield; harvestedYield = _stake.harvestedYield; lastHarvestTime = _stake.lastHarvestTime; if (_now() > endTime) { harvestableYield = totalYield.sub(harvestedYield); } else { harvestableYield = totalYield.mul(_now().sub(lastHarvestTime)).div(endTime.sub(startTime)); } } // Returns block.timestamp, overridable for test purposes. function _now() internal view virtual returns (uint256) { return block.timestamp; } }
unallocated (excess) tokens can be withdrawn by the contract owner not earlier than 18 months
uint256 public constant WITHDRAWAL_LOCKUP_DURATION = 30 days * 18;
1,735,184
[ 1, 318, 28172, 261, 338, 614, 13, 2430, 848, 506, 598, 9446, 82, 635, 326, 6835, 3410, 486, 13805, 2353, 6549, 8846, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5381, 13601, 40, 10821, 1013, 67, 6589, 3079, 67, 24951, 273, 5196, 4681, 380, 6549, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//////////////////////////////////////////////////////////////////////////////// ///////////////////////////////// ERC223 /////////////////////////////////////// library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract ERC223Interface { function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public ; function transfer(address to, uint value, bytes data) public ; //event Transfer(address indexed from, address indexed to, uint value, bytes data); event Transfer(address indexed from, address indexed to, uint value); //ERC 20 style } contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) public; } contract EducationToken is ERC223Interface { using SafeMath for uint; string public constant name = "Education Token Test"; string public constant symbol = "KEDUTest"; uint8 public constant decimals = 18; uint256 public constant totalSupply = 2 * (10 ** 9) * (10 ** 18); // 2 billion "KEDU" uint256 public constant Million = (10 ** 6); //uint256 public nowSupply = 0; address public constant contractOwner = 0x21bA616f20a14bc104615Cc955F818310E725aBA; mapping (address => uint256) balances; function EducationToken() { preAllocation(); } function preAllocation() internal { balances[0x21bA616f20a14bc104615Cc955F818310E725aBA] = 0*(10**6)*(10**18); // 0% ,code writer balances[0x6F34740F96C76B4C228D8EFA5EC9C71205733102] = 200*(10**6)*(10**18); // 10% ,contractOwner1 balances[0x33fa06cD9A1451961890532bB3F2F2b6fB817976] = 200*(10**6)*(10**18); // 10% ,contractOwner2 balances[0x5d49508ab79A149663F036C9e1f820F2B78EC230] = 200*(10**6)*(10**18); // 10% ,contractOwner3 balances[0x45bC7Ac57f10b42133abf5a92861D4AA3C5EA3e8] = 200*(10**6)*(10**18); // 10% ,contractOwner4 balances[0xc157F7DcA6c101Cc2c63462d4E81bF5C335EFB49] = 200*(10**6)*(10**18); // 10% ,contractOwner5 balances[0x1306E082444370f11039b1eC19D85Bf3dF35Bb62] = 200*(10**6)*(10**18); // 10% ,contractOwner6 balances[0xC45E047cD81356d655D5c061311f62BBe2d2908C] = 200*(10**6)*(10**18); // 10% ,contractOwner7 balances[0x42b4B6BBb2619Afd619A56aeBa1533699c3A8e8d] = 200*(10**6)*(10**18); // 10% ,contractOwner8 balances[0xA8e5986C88556180Db85b3288CD10f383c1C04a6] = 200*(10**6)*(10**18); // 10% ,contractOwner9 balances[0xA6B60801869c732B75Ee980fC53458dAc75ebe7E] = 200*(10**6)*(10**18); // 10% ,contractOwner10 } function() payable { require(msg.value >= 0.00001 ether); } function getETH(uint256 _amount) public { //require(now>endTime); require(msg.sender==contractOwner); msg.sender.transfer(_amount); } function nowSupply() constant public returns(uint){ uint supply=totalSupply; supply=supply-balances[0x21bA616f20a14bc104615Cc955F818310E725aBA]; supply=supply-balances[0x6F34740F96C76B4C228D8EFA5EC9C71205733102]; supply=supply-balances[0x33fa06cD9A1451961890532bB3F2F2b6fB817976]; supply=supply-balances[0x5d49508ab79A149663F036C9e1f820F2B78EC230]; supply=supply-balances[0x45bC7Ac57f10b42133abf5a92861D4AA3C5EA3e8]; supply=supply-balances[0xc157F7DcA6c101Cc2c63462d4E81bF5C335EFB49]; supply=supply-balances[0x1306E082444370f11039b1eC19D85Bf3dF35Bb62]; supply=supply-balances[0xC45E047cD81356d655D5c061311f62BBe2d2908C]; supply=supply-balances[0x42b4B6BBb2619Afd619A56aeBa1533699c3A8e8d]; supply=supply-balances[0xA8e5986C88556180Db85b3288CD10f383c1C04a6]; supply=supply-balances[0xA6B60801869c732B75Ee980fC53458dAc75ebe7E]; return supply; } ///////////////////////////////////////////////////////////////////// ///////////////// ERC223 Standard functions ///////////////////////// ///////////////////////////////////////////////////////////////////// function transfer(address _to, uint _value, bytes _data) public { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } require(_value > 0); require(balances[msg.sender] >= _value); require(balances[_to]+_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } emit Transfer(msg.sender, _to, _value); } function transfer(address _to, uint _value) public { uint codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } require(_value > 0); require(balances[msg.sender] >= _value); require(balances[_to]+_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } emit Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } }
10% ,contractOwner5
balances[0xc157F7DcA6c101Cc2c63462d4E81bF5C335EFB49] = 200*(10**6)*(10**18);
2,504,562
[ 1, 2163, 9, 269, 16351, 5541, 25, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 324, 26488, 63, 20, 6511, 27985, 42, 27, 40, 71, 37, 26, 71, 15168, 39, 71, 22, 71, 4449, 8749, 22, 72, 24, 41, 11861, 70, 42, 25, 39, 3707, 25, 41, 22201, 7616, 65, 273, 4044, 21556, 2163, 636, 26, 17653, 12, 2163, 636, 2643, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x4e3981e983dA718Bd4892629088BC230284Cb682/sources/SushiMaker.sol
M1 - M5: OK C1 - C24: OK C6: It's not a fool proof solution, but it prevents flash loans, so here it's ok to use tx.origin Try to make flash-loan exploit harder to do by only allowing externally owned addresses.
modifier onlyEOA() { require(msg.sender == tx.origin, "SushiMaker: must use EOA"); _; }
727,214
[ 1, 49, 21, 300, 490, 25, 30, 7791, 385, 21, 300, 385, 3247, 30, 7791, 385, 26, 30, 2597, 1807, 486, 279, 284, 1371, 14601, 6959, 16, 1496, 518, 17793, 9563, 437, 634, 16, 1427, 2674, 518, 1807, 1529, 358, 999, 2229, 18, 10012, 6161, 358, 1221, 9563, 17, 383, 304, 15233, 305, 17895, 765, 358, 741, 635, 1338, 15632, 18885, 1230, 16199, 6138, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 41, 28202, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 2229, 18, 10012, 16, 315, 55, 1218, 77, 12373, 30, 1297, 999, 512, 28202, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xB2DD8723a1Ec63d9e6f4538c203fe0Bd23341056/sources/BusdToGfiFarm.sol
TODO - _coinAge need to be divided with 1 days instead of 30 which is hardcoded
function getCoinAge (address _address, uint _index) public view returns (uint _coinAge) { uint256 nCoinSeconds = now.sub(uint(stakingInfo[_address][_index].stakingTime)); _coinAge = nCoinSeconds.div(30); }
5,260,949
[ 1, 6241, 300, 389, 12645, 9692, 1608, 358, 506, 26057, 598, 404, 4681, 3560, 434, 5196, 1492, 353, 7877, 24808, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1927, 885, 9692, 261, 2867, 389, 2867, 16, 2254, 389, 1615, 13, 1071, 1476, 1135, 261, 11890, 389, 12645, 9692, 13, 288, 203, 203, 540, 2254, 5034, 225, 290, 27055, 6762, 273, 2037, 18, 1717, 12, 11890, 12, 334, 6159, 966, 63, 67, 2867, 6362, 67, 1615, 8009, 334, 6159, 950, 10019, 203, 3639, 389, 12645, 9692, 273, 290, 27055, 6762, 18, 2892, 12, 5082, 1769, 203, 5411, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/100/0x41Eb60C02d84865334b4105CEE9D25341402b004/sources/Vesting.sol
Time of deployment of this contract
uint256 public deployment;
16,645,762
[ 1, 950, 434, 6314, 434, 333, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 6314, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x8183703E9DF90ed76bec0b0b8fAD33f2c024Be59/sources/KingOfEthResourcesInterface.sol
@dev The houses contract's address @dev Only the houses contract can run this function
{ require(housesContract == msg.sender); _; }
4,454,611
[ 1, 1986, 366, 1481, 281, 6835, 1807, 1758, 225, 5098, 326, 366, 1481, 281, 6835, 848, 1086, 333, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 2583, 12, 76, 1481, 281, 8924, 422, 1234, 18, 15330, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]